Python Interview Questions for Freshers (With Answers)

Last updated (2026-11-02)

These Python interview questions for freshers cover what campus drives, service companies and product startups actually ask in a first technical round. Every answer is written for Python 3.12, with notes wherever behaviour depends on the version or on CPython specifically.

Read an answer, then close the page and explain it out loud in your own words. Interviewers care less about memorised definitions and more about whether you can predict what a short snippet prints and why.

How to use these Python interview questions for freshers with answers

Freshers are usually tested on four things: core language behaviour, built-in collections, OOP concepts and a couple of small coding problems. The groups below follow that order.

  • Run every snippet yourself in a Python 3.12 REPL. Seeing the output once sticks better than reading it twice.
  • For each question, prepare a one-line definition, a tiny example and one practical consequence.
  • Pair this page with DSA practice from the DSA sheets, since most coding rounds use Python only as the language, not the topic.
  • When you feel ready, rehearse under pressure with an AI mock interview.
If a question has a CPython-specific answer (small integer caching, reference counting, the GIL), say so. Mentioning that it is an implementation detail is itself a strong signal.

Python basics

Language fundamentals that open almost every Python interview.

1.What are the key features of Python?

  • Interpreted and dynamically typed: types are checked at runtime, and a variable can be rebound to any object.
  • Strongly typed: Python will not silently convert '1' + 1; it raises a TypeError.
  • Multi-paradigm: procedural, object-oriented and functional styles all work.
  • Batteries included: a large standard library (collections, itertools, json, pathlib, and more).

Strictly speaking, CPython compiles source to bytecode first and then interprets that bytecode on its virtual machine.

2.What is the difference between `is` and `==`?

== compares values by calling __eq__. is checks identity, meaning both names point to the same object in memory (same id()).

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True, same contents
print(a is b)  # False, two different list objects
print(a is a)  # True

Use is only for singletons such as None (if x is None). Results like 256 is 256 being True come from CPython caching small integers (-5 to 256), which is an implementation detail you should never rely on.

3.What is the difference between mutable and immutable objects?

A mutable object can be changed in place after creation: list, dict, set, bytearray and most user-defined objects. An immutable object cannot: int, float, str, tuple, frozenset, bytes.

Operations that look like they modify an immutable object, such as s += 'x' on a string, actually create a new object and rebind the name. Only hashable objects (which in practice means immutable ones, with hashable contents) can be dict keys or set members.

4.How does Python pass arguments to functions?

Python uses pass by object reference (also called pass by assignment). The parameter becomes a new name bound to the same object the caller passed.

If the function mutates a mutable object, such as lst.append(1), the caller sees the change. If it rebinds the parameter, such as lst = [], the caller's variable is unaffected.

5.What does `if __name__ == '__main__':` do?

When a file is run directly, Python sets its __name__ to '__main__'. When the same file is imported, __name__ is the module name instead.

Code under this check therefore runs only when the file is executed as a script, not when another module imports it. It is the standard place for a main() call or quick tests.

Data types and collections

Lists, tuples, dicts and sets come up in almost every round, often as output-prediction questions.

6.What is the difference between a list and a tuple?

Aspectlisttuple
MutabilityMutableImmutable
Syntax[1, 2](1, 2) or 1, 2
HashableNoYes, if all items are hashable
Typical useGrowing collection of similar itemsFixed record, dict key, multiple return values
MemorySlightly larger (over-allocates for appends)Slightly smaller

A one-element tuple needs a trailing comma: (5,). Note that a tuple holding a list is still immutable as a tuple, but the inner list can change.

7.Are Python dictionaries ordered?

Yes. Since Python 3.7, the language guarantees that a dict preserves insertion order (in CPython 3.6 it was already true, but only as an implementation detail).

Updating an existing key keeps its original position. collections.OrderedDict is still useful for move_to_end() and for order-sensitive equality comparisons.

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

A shallow copy creates a new outer container but reuses references to the same inner objects. A deep copy recursively copies the inner objects as well.

import copy

grid = [[1, 2], [3, 4]]
shallow = copy.copy(grid)     # same as grid.copy() or grid[:]
deep = copy.deepcopy(grid)

grid[0].append(99)
print(shallow[0])  # [1, 2, 99], inner list is shared
print(deep[0])     # [1, 2], fully independent

Plain assignment (b = a) copies nothing at all; both names point to the same object.

9.What will `[[0] * 3] * 3` give you, and why is it a trap?

It looks like a 3 by 3 grid, but the outer * 3 repeats a reference to the same inner list three times. Setting grid[0][0] = 1 changes the first element of every row.

Build independent rows with a comprehension instead: [[0] * 3 for _ in range(3)].

10.What is slicing, and how do you reverse a sequence?

Slicing uses seq[start:stop:step], where stop is exclusive and any part can be omitted. Negative indices count from the end, so s[-1] is the last item.

s[::-1] returns a reversed copy. For lists, lst.reverse() reverses in place and returns None, while reversed(lst) returns a lazy iterator.

11.What are list, dict and set comprehensions?

Comprehensions build a collection from an iterable in one expression, with an optional filter. They are usually clearer and a bit faster than an equivalent loop with append.

squares = [n * n for n in range(10) if n % 2 == 0]
lengths = {word: len(word) for word in ["py", "java"]}
unique_chars = {ch for ch in "banana"}

In Python 3.12, comprehensions are inlined (PEP 709), which makes them faster, but their loop variable still does not leak into the surrounding scope.

Functions, scope, decorators and generators

This group separates candidates who have only written scripts from those who understand how Python executes code.

12.What are `*args` and `**kwargs`?

*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. The names are convention; the * and ** are what matter.

def log(level, *args, **kwargs):
    print(level, args, kwargs)

log("INFO", 1, 2, user="asha")
# INFO (1, 2) {'user': 'asha'}

nums = [3, 4]
print(max(*nums))  # unpacking at the call site

Parameter order is: positional, *args, keyword-only, **kwargs. A bare * forces the parameters after it to be keyword-only, and a / (Python 3.8+) marks the ones before it as positional-only.

13.Why are mutable default arguments dangerous?

Default values are evaluated once, when the def statement runs, not on every call. A mutable default such as a list is therefore shared across all calls that use it.

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

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2], same list reused!

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

14.Explain the LEGB rule and the `global` and `nonlocal` keywords.

Python resolves a name by searching Local, then Enclosing function scopes, then Global (module), then Built-in. The first match wins.

Assigning to a name inside a function makes it local by default. global x lets the function rebind a module-level x, and nonlocal x lets a nested function rebind a variable in its enclosing function.

15.What is a decorator? Write a simple one.

A decorator is a callable that takes a function and returns a new function, usually adding behaviour before or after the original call. @timer above a def is shorthand for func = timer(func).

import functools
import time

def timer(func):
    @functools.wraps(func)  # keeps __name__ and docstring
    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

Decorators rely on closures: wrapper remembers func from the enclosing scope even after timer has returned.

16.What is a generator, and how does `yield` differ from `return`?

A function containing yield returns a generator object when called. Each next() resumes execution until the next yield, producing one value at a time and keeping local state between calls.

return ends the function for good (inside a generator it raises StopIteration). Generators are ideal for large or infinite streams because they never build the whole sequence in memory.

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

[x * x for x in data] builds the entire list in memory immediately. (x * x for x in data) creates a lazy generator that produces items only when iterated, and can be consumed only once.

Use a generator expression when you only need to iterate once, especially with functions like sum(x * x for x in data). Use a list when you need indexing, len() or multiple passes.

18.What is the difference between an iterable and an iterator?

An iterable is anything you can loop over; it implements __iter__ and returns a fresh iterator each time (lists, strings, dicts). An iterator implements __next__, remembers its position, and is exhausted after one pass.

A for loop calls iter() on the iterable and then next() repeatedly until StopIteration is raised. Every generator is an iterator.

Python OOPs interview questions

Classes, inheritance and dunder methods. For the language-independent theory, revise the OOP core subject notes.

19.What is the difference between `__init__` and `__new__`?

__new__ is a static method that creates and returns the new instance; it runs first. __init__ then initialises that already-created instance and must return None.

You rarely override __new__. Common reasons are subclassing immutable types like int or str (their value is fixed at creation), or controlling instance creation, as in a singleton.

20.What is the difference between instance, class and static methods?

class Student:
    school = "DPS"  # class attribute

    def __init__(self, name):
        self.name = name  # instance attribute

    def greet(self):                 # instance method
        return f"Hi, {self.name}"

    @classmethod
    def from_csv(cls, row):          # gets the class
        return cls(row.split(",")[0])

    @staticmethod
    def is_valid_name(name):         # gets neither
        return name.isalpha()

Class methods are typically used as alternative constructors and work correctly with subclasses because they receive cls. Static methods are plain functions grouped under the class for organisation.

21.How does inheritance work, and what is the MRO?

A class can inherit from one or more base classes. Python supports single, multilevel, hierarchical and multiple inheritance (see types of inheritance).

The Method Resolution Order (MRO) is the order in which Python searches classes for an attribute. It is computed with the C3 linearization algorithm, which keeps every child before its parents and preserves the left-to-right order of bases. Inspect it with ClassName.__mro__ or ClassName.mro().

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print([k.__name__ for k in D.__mro__])
# ['D', 'B', 'C', 'A', 'object']

22.What does `super()` do?

super() returns a proxy that delegates to the next class in the MRO of the current instance, not simply the direct parent. In single inheritance those are the same thing.

In multiple inheritance, calling super().__init__() in every class makes each initialiser run exactly once, in MRO order. That cooperative behaviour is why super() is preferred over calling Parent.__init__(self) directly.

23.How is encapsulation done in Python? What is name mangling?

Python has no enforced private keyword. By convention, a single leading underscore (_balance) means internal, do not touch from outside.

A double leading underscore (__balance) triggers name mangling: inside class Account it is stored as _Account__balance. This mainly prevents accidental clashes in subclasses; it is not real access control. Use @property to expose a controlled getter and setter.

24.How do you achieve polymorphism and abstraction in Python?

Polymorphism comes from method overriding and duck typing: if an object has the method you call, it works, regardless of its class. Python has no method overloading by signature; a later def with the same name simply replaces the earlier one.

Abstraction uses the abc module: subclass ABC and mark methods with @abstractmethod. A class with unimplemented abstract methods cannot be instantiated.

25.What are dunder (magic) methods? Give examples.

Dunder methods (double underscore, like __len__) let your class hook into built-in syntax and functions. Python calls them for you.

  • __str__ for print() and str(), __repr__ for the developer-facing representation.
  • __eq__ and __hash__ for == and use as dict keys (defining __eq__ alone makes instances unhashable).
  • __len__, __getitem__, __iter__ and __contains__ for container behaviour.
  • __add__, __lt__ and friends for operator overloading.
  • __enter__ and __exit__ for the with statement.

Python coding interview questions with short solutions

Short problems where the interviewer wants idiomatic Python and a stated time complexity. For harder problems, follow the DSA patterns.

26.Check whether a string is a palindrome, ignoring case and non-alphanumeric characters.

def is_palindrome(s: str) -> bool:
    cleaned = [ch.lower() for ch in s if ch.isalnum()]
    return cleaned == cleaned[::-1]

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

O(n) time and O(n) extra space. Mention the two-pointer version if asked for O(1) extra space.

27.Find two numbers in a list that add up to a target (two sum).

def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    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)

One pass with a dict gives O(n) time instead of the O(n squared) nested loop.

28.Count the frequency of each character or word.

from collections import Counter

counts = Counter("mississippi")
print(counts.most_common(2))  # [('i', 4), ('s', 4)]

# Without Counter:
freq = {}
for ch in "mississippi":
    freq[ch] = freq.get(ch, 0) + 1

Know both: the interviewer may ask you to avoid the library. Among equal counts, most_common keeps first-seen order.

29.Remove duplicates from a list while preserving order.

items = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(items)))  # [3, 1, 2]

This works because dicts keep insertion order. list(set(items)) also removes duplicates but does not preserve the original order.

30.Check whether two strings are anagrams.

from collections import Counter

def is_anagram(a: str, b: str) -> bool:
    return Counter(a) == Counter(b)

print(is_anagram("listen", "silent"))  # True

O(n) with counting. sorted(a) == sorted(b) is also correct but O(n log n).

31.Write a generator that yields the first n Fibonacci numbers.

def fibonacci(n: int):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fibonacci(7)))  # [0, 1, 1, 2, 3, 5, 8]

Tuple unpacking (a, b = b, a + b) evaluates the right side first, so no temporary variable is needed.

32.Flatten an arbitrarily nested list.

def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print(list(flatten([1, [2, [3, 4]], 5])))  # [1, 2, 3, 4, 5]

yield from delegates to the recursive generator. Very deep nesting can hit the recursion limit (1000 by default), so mention an explicit stack as the alternative.

Memory management, the GIL and error handling

Fewer freshers prepare these, so a precise answer here stands out.

33.How does Python manage memory?

CPython mainly uses reference counting: every object tracks how many references point to it, and it is freed as soon as the count reaches zero. A separate cyclic garbage collector (the gc module) finds and frees reference cycles that counting alone cannot.

All objects live on a private heap managed by the interpreter, and small objects are served by a specialised allocator (pymalloc). You never free memory manually.

34.What is the GIL, and how does it affect multithreading?

The Global Interpreter Lock is a mutex in CPython that lets only one thread execute Python bytecode at a time. It keeps reference counting simple and safe, but it means CPU-bound threads do not run in parallel on multiple cores.

  • I/O-bound work (network calls, file reads): threads or asyncio still help, because the GIL is released while waiting.
  • CPU-bound work: use multiprocessing or concurrent.futures.ProcessPoolExecutor, or libraries like NumPy that release the GIL in native code.
Python 3.12 always has the GIL. Python 3.13 added an optional, experimental free-threaded build without the GIL (PEP 703); 3.14 made that build officially supported but still optional, and the standard build keeps the GIL.

35.Explain `try`, `except`, `else` and `finally`.

try:
    value = int(user_input)
except ValueError as e:
    print("Not a number:", e)
else:
    print("Parsed:", value)   # runs only if no exception
finally:
    print("Always runs")      # cleanup, even after return

Catch specific exceptions rather than a bare except:, which also swallows KeyboardInterrupt and SystemExit. Use raise with no arguments to re-raise the current exception.

36.What is a context manager?

A context manager sets something up and guarantees cleanup, used with the with statement. with open('data.txt') as f: closes the file even if an exception occurs inside the block.

You can write one as a class with __enter__ and __exit__, or as a generator decorated with contextlib.contextmanager.

Put this guide to work

Build a one-page resume, check it against a real job description, then practice your answers out loud.

Frequently asked questions

Where can I practise Python interview questions for freshers with answers?

Work through the grouped questions on this page in a Python 3.12 REPL, then practise answering them out loud in an AI mock interview. Add daily DSA problems in Python so the coding round feels routine.

Which Python topics are most important for a fresher interview?

Data types and mutability, lists versus tuples, dictionaries, functions with args and kwargs, comprehensions, generators, decorators, OOP with inheritance and the MRO, and exception handling. Most rounds also include one or two short coding problems.

How should I prepare for Python coding interview questions?

Learn the common DSA patterns such as two pointers, sliding window and hashing, and solve them in idiomatic Python using dict, set, Counter and slicing. Always state the time and space complexity of your solution.

Are Python OOPs interview questions asked to freshers?

Yes, OOP is a standard fresher topic. Expect questions on classes and objects, the four pillars, init versus new, instance, class and static methods, inheritance with super and the MRO, and dunder methods.

Which Python version should I learn for interviews?

Learn Python 3, ideally a recent release such as 3.12. Python 2 reached end of life in 2020, and interviewers expect Python 3 syntax and behaviour.