Title text Python Interview Questions for Freshers on a CertTulen branded background
Back to Blog
Python Interview questions Freshers Placements

Python Interview Questions for Freshers (2026): 25 with Answers

By Abirami Seeni8 min read

Python interviews for freshers usually test four things: how the language treats objects and names, the built-in data structures, basic object-oriented programming, and error handling, followed by a small coding task. Below are 25 questions that come up again and again, each with a short answer and code you can run. Every example was tested on Python 3.13 and uses nothing that changed in later versions.

At a glance

SectionQuestionsWhat it tests
Basics1 to 6Objects, names and function arguments
Data structures7 to 12Choosing and using built-in types
Functions and OOP13 to 18Classes, methods and decorators
Errors and runtime19 to 22Exceptions, Python style, the GIL
Practical coding23 to 25Small problems solved live

How to use this page: read the answer, close the page, then type the code from memory and run it. Interviewers can tell the difference between a memorised definition and a concept you have actually used.

Basics (questions 1 to 6)

1. Is Python compiled or interpreted?

Both, in a sense. CPython, the standard implementation, first compiles your source code to bytecode (cached as .pyc files in __pycache__), then its virtual machine executes that bytecode. You never run a separate compile step, which is why Python is usually called interpreted.

2. What is the difference between mutable and immutable types?

A mutable object can change after it is created; an immutable one cannot. Lists, dictionaries and sets are mutable. Numbers, strings, tuples and frozensets are immutable, so "changing" them creates a new object.

city = "chennai"
print(city.upper(), city)   # CHENNAI chennai  (original unchanged)
marks = [70, 80]
marks.append(90)
print(marks)                # [70, 80, 90]  (same list, changed)

Only immutable (more precisely, hashable) objects can be dictionary keys or set members.

3. What is the difference between is and ==?

== compares values. is checks whether two names point to the same object. Use is only for singletons such as None.

a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)   # True False True

A common mistake is writing if x is 10. It may appear to work for small numbers, but you cannot rely on it. Write x == 10, and x is None for None checks.

4. Does Python pass arguments by value or by reference?

Neither label fits exactly. The Python FAQ says arguments are passed by assignment: the function parameter becomes a new name for the same object. Changing a mutable object inside the function is visible outside; rebinding the name is not.

def add_item(items):
    items.append(4)      # changes the shared list

def replace(items):
    items = [0]          # only rebinds the local name

nums = [1, 2, 3]
add_item(nums)
replace(nums)
print(nums)              # [1, 2, 3, 4]

5. What are *args and **kwargs?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. The names are convention; the stars do the work.

def report(*args, **kwargs):
    print(args)      # (10, 20)
    print(kwargs)    # {'city': 'Pune', 'year': 2026}

report(10, 20, city="Pune", year=2026)

6. Why is a mutable default argument dangerous?

Default values are created once, when the function is defined, not on every call. A default list therefore keeps growing across calls. Use None and create the list inside.

def add_bad(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add_bad("a"), add_bad("b"))   # ['a', 'b'] ['a', 'b']

def add_good(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(add_good("a"), add_good("b")) # ['a'] ['b']

Interviewers like this question because it shows whether you understand when Python evaluates code. Explain why it happens, not just the fix.

Data structures (questions 7 to 12)

7. When do you use a list, tuple, set or dictionary?

TypeOrderedMutableUse it for
listYesYesA sequence you add to or sort
tupleYesNoFixed records, dictionary keys
setNoYesUnique items, fast membership tests
dictInsertion orderYesKey to value lookups

Membership tests (x in s) on a set or dictionary are fast on average, while on a list Python checks item by item. That one fact answers many "optimise this code" questions.

8. What is the difference between a list comprehension and a generator expression?

A list comprehension builds the whole list in memory. A generator expression produces items one at a time, which saves memory for large data, but you can loop over it only once.

squares = [n * n for n in range(5)]
print(squares)              # [0, 1, 4, 9, 16]

gen = (n * n for n in range(5))
print(sum(gen))             # 30
print(sum(gen))             # 0  (already used up)

9. Are dictionaries ordered?

Yes. Since Python 3.7, keeping insertion order is part of the language definition, not just a CPython detail. Sorting is still your job: use sorted(d.items()) if you need keys in alphabetical order.

10. What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new outer container but shares the inner objects. A deep copy copies everything recursively.

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow)   # [[1, 2, 99], [3, 4]]
print(deep)      # [[1, 2], [3, 4]]

11. How do you remove duplicates from a list but keep the original order?

set() removes duplicates but loses order. Because dictionaries keep insertion order, dict.fromkeys() does both.

cities = ["Delhi", "Pune", "Delhi", "Kochi", "Pune"]
print(list(dict.fromkeys(cities)))   # ['Delhi', 'Pune', 'Kochi']

12. How does slicing work?

The syntax is seq[start:stop:step]. start is included, stop is excluded, and negative numbers count from the end.

s = "python"
print(s[1:4], s[-1], s[::2], s[::-1])   # yth n pto nohtyp

Functions and OOP (questions 13 to 18)

13. What is self, and what does __init__ do?

self is the instance a method is called on. Python passes it automatically, so acc.deposit(100) becomes Account.deposit(acc, 100). __init__ is the initialiser: it runs after the object is created and sets its starting attributes. It is not technically the constructor; __new__ creates the object.

14. What is the difference between a class attribute and an instance attribute?

A class attribute is shared by every instance. An instance attribute, set on self, belongs to one object. Putting a mutable object in a class attribute is a classic bug.

class Student:
    subjects = []               # shared by all students
    def __init__(self, name):
        self.name = name        # belongs to one student

asha, ravi = Student("Asha"), Student("Ravi")
asha.subjects.append("Maths")
print(ravi.subjects)            # ['Maths']  (surprise)

15. How do inheritance and super() work?

A child class inherits methods and attributes from its parent. super() calls the parent's version, most often in __init__. Python decides which class to search first using the method resolution order (MRO).

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

class SavingsAccount(Account):
    def __init__(self, owner, balance=0, rate=0.04):
        super().__init__(owner, balance)
        self.rate = rate

acc = SavingsAccount("Meena", 1000)
print(acc.owner, acc.balance, acc.rate)            # Meena 1000 0.04
print([c.__name__ for c in SavingsAccount.__mro__]) # ['SavingsAccount', 'Account', 'object']

16. What is the difference between an instance method, a class method and a static method?

An instance method receives self and works on one object. A class method receives cls and is often used as an alternative constructor. A static method receives neither and is a helper that lives in the class for organisation.

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def to_fahrenheit(self):
        return self.celsius * 9 / 5 + 32

    @classmethod
    def from_fahrenheit(cls, f):
        return cls((f - 32) * 5 / 9)

    @staticmethod
    def is_valid(celsius):
        return celsius >= -273.15

t = Temperature.from_fahrenheit(212)
print(t.celsius, t.to_fahrenheit(), Temperature.is_valid(-300))   # 100.0 212.0 False

17. What is the difference between __str__ and __repr__?

__str__ gives a readable form for users and is what print() shows. __repr__ gives an unambiguous form for developers and is used in the shell and inside containers. If you write only one, write __repr__.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(2, 3)
print(p, [p])    # (2, 3) [Point(x=2, y=3)]

18. What is a decorator? Write one.

A decorator is a function that takes a function and returns a new one, usually adding behaviour around it. @timed above a function is shorthand for total = timed(total). Use functools.wraps so the wrapped function keeps its name and docstring.

import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
        return result
    return wrapper

@timed
def total(n):
    return sum(range(n))

print(total(1_000_000))   # prints the time, then 499999500000
print(total.__name__)     # total

Errors and runtime (questions 19 to 22)

19. How do try, except, else and finally work together?

try holds code that might fail. except handles a specific error. else runs only if no error occurred. finally always runs, even after a return, which makes it the place for clean-up.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    else:
        return result
    finally:
        print("Always runs")

print(safe_divide(10, 2))   # Always runs, then 5.0
print(safe_divide(1, 0))    # Cannot divide by zero, Always runs, None

Catch specific exceptions. A bare except: hides real bugs and is a red flag in code reviews.

20. How do you create and raise a custom exception?

Subclass Exception, give it a clear name, and raise it with a helpful message.

class InsufficientBalanceError(Exception):
    """Raised when a withdrawal is larger than the balance."""

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(f"Balance {balance}, requested {amount}")
    return balance - amount

try:
    withdraw(500, 800)
except InsufficientBalanceError as err:
    print("Error:", err)    # Error: Balance 500, requested 800

21. What do EAFP and LBYL mean?

EAFP, "easier to ask for forgiveness than permission", is the usual Python style: try the operation and catch the exception. LBYL, "look before you leap", checks first. EAFP avoids race conditions, for example a file deleted between your check and your open. For dictionaries, get() often beats both.

prices = {"pen": 10}
try:
    print(prices["book"])
except KeyError:
    print("not found")
print(prices.get("book", 0))   # 0

22. What is the GIL, and does Python still have it?

The global interpreter lock is the mechanism that lets only one thread execute Python bytecode at a time in CPython. Threads still help with I/O-bound work such as network calls, but CPU-heavy work needs multiprocessing or native libraries. Since Python 3.14, a separate free-threaded build without the GIL is officially supported (PEP 779), while the standard build still uses the GIL. Mentioning this shows you follow the language.

Practical coding (questions 23 to 25)

Interviewers watch how you think as much as the result. Say your approach aloud, handle edge cases, then state the time complexity.

23. Check whether a string is a palindrome, ignoring case and punctuation

def is_palindrome(text):
    cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("Malayalam"))                        # True
print(is_palindrome("A man, a plan, a canal: Panama"))   # True
print(is_palindrome("Python"))                           # False

This runs in O(n) time. Mention that an empty string counts as a palindrome here, and ask the interviewer whether that is acceptable.

24. Count how often each word appears

from collections import Counter

text = "data analyst data engineer data scientist analyst"
counts = Counter(text.split())
print(counts.most_common(2))   # [('data', 3), ('analyst', 2)]

If the interviewer says "no imports", build the same result with a dictionary and counts[word] = counts.get(word, 0) + 1.

25. Two sum: find the positions of two numbers that add up to a target

The brute-force answer checks every pair, which is O(n²). The expected answer uses a dictionary of values already seen, which is O(n).

def two_sum(nums, target):
    seen = {}                          # value -> index
    for i, n in enumerate(nums):
        if target - n in seen:
            return seen[target - n], i
        seen[n] = i
    return None

print(two_sum([2, 7, 11, 15], 9))   # (0, 1)
print(two_sum([3, 2, 4], 6))        # (1, 2)
print(two_sum([1, 2], 7))           # None

How to prepare in the last two weeks

  1. Days 1 to 5: go through questions 1 to 22 and run every example yourself. Change one line at a time and predict the output before you run it.
  2. Days 6 to 10: solve two small problems a day on paper first, then in a plain editor without autocomplete, because live coding rounds rarely allow AI help.
  3. Days 11 to 14: do timed mock rounds with a friend and practise explaining your code aloud.

Bring one project you can talk about for five minutes: what problem it solves, one bug you fixed and what you would improve. A clean GitHub repository helps here. If you are choosing between certifications to show your Python level, our PCEP vs PCAP comparison explains which fits a fresher.

How CertTulen Academy can help

CertTulen Academy runs live, instructor-led Python training with hands-on labs. The Python Entry-Level Programming (PCEP) course builds the basics behind questions 1 to 12. The PCAP course goes deeper into OOP, exceptions and modules, which covers most of questions 13 to 22. Our PCEP exam guide for India explains the certification itself. Message us on WhatsApp at +91 93618 83583 or use our contact page to find a batch that suits you.

Frequently Asked Questions

How much Python do I need to know for a fresher interview?+

Enough to write and explain small programs without help: variables and types, loops and conditions, functions, lists, dictionaries and sets, string handling, basic classes and exceptions. You should also be able to read an error message and fix it. Libraries such as pandas matter for data roles, but interviewers usually check the core language first.

Should I learn data structures and algorithms in Python or in C++ or Java?+

If the company lets you choose the language, Python is a sound choice because the code is short and readable, which leaves more time to explain your approach. Learn the time complexity of list, set and dictionary operations, because many interview follow-ups ask how your solution scales. Check the job description in case a specific language is required.

Are Python certifications like PCEP useful for freshers?+

They help as structured proof that you know the fundamentals, especially if your degree is not in computer science. They do not replace projects or a live coding round. A certificate plus two small, well-documented projects on GitHub gives an interviewer something concrete to ask about.

What Python projects should a fresher put on a resume?+

Pick projects that show a full workflow rather than a copied tutorial: a script that cleans a messy CSV and produces a report, a small Flask or FastAPI app with a database, or a data analysis notebook on Indian open data with clear conclusions. Be ready to explain every line, one bug you fixed, and what you would improve.

How do I practise Python coding without a laptop?+

You can write and run Python in a browser on most phones and lab computers, for example in an online notebook or a cloud code editor, and you can solve problems on paper first. Paper practice is useful anyway, because it trains you to plan the logic before typing, which is exactly what interviewers watch for.

Sources

Checked on 25 October 2026. Exams, products and rules change, so confirm on the official page before you book or decide.

Written by

Abirami Seeni

Microsoft Certified Trainer (MCT), founder of CertTulen Academy

CertTulen Academy · Microsoft Training Services Partner · Microsoft AI Cloud Partner

Read next

Chat with us