These python interview questions cover freshers to experienced developers — data types, mutability, OOP, decorators, generators, the GIL and common coding tasks — each with a short, correct model answer you can adapt in your own words during the interview.

Beginner python interview questions

Q: What are Python’s core built-in data types?

A: The common ones are int, float, complex, bool, str, list, tuple, range, dict, set and frozenset, plus NoneType for None. Strings, tuples and frozensets are immutable; lists, dicts and sets are mutable. Knowing which are hashable matters because only hashable objects can be dictionary keys or set members.

Q: What is the difference between a list and a tuple?

A: A list is mutable and defined with square brackets; a tuple is immutable and uses parentheses. Tuples are slightly faster and can be used as dictionary keys because they are hashable, while lists cannot. Use tuples for fixed records and lists for collections you will modify.

Q: What does mutable versus immutable mean?

A: A mutable object can change in place after creation (list, dict, set); an immutable object cannot (int, str, tuple). Reassigning an immutable variable creates a new object and rebinds the name. This matters for function arguments and default values, since mutable defaults are shared across calls.

Q: Why should you avoid mutable default arguments?

A: A default value is evaluated once when the function is defined, so a mutable default persists between calls and accumulates data unexpectedly. Use None as the sentinel instead.

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

Q: What is the difference between is and == ?

A: == compares values for equality; is compares identity, meaning whether two names point to the same object in memory. Use == for value checks and is only for singletons like None. Small integers and short strings may be cached, so relying on is for values is unsafe.

Q: How do you reverse a string in Python?

A: The idiomatic way is slicing with a step of minus one, which is concise and fast.

text = 'jobs'
print(text[::-1])   # 'sboj'

Q: What is a list comprehension?

A: It is a compact way to build a list from an iterable, optionally with a filter. It is usually faster and clearer than an equivalent for loop.

squares = [n*n for n in range(6) if n % 2 == 0]
# [0, 4, 16]

Intermediate python interview questions

Q: How does Python manage memory?

A: CPython uses reference counting as the primary mechanism — an object is freed when its count drops to zero — backed by a cyclic garbage collector that reclaims reference cycles. Memory is organised in private heaps and object pools. You rarely free memory manually, but you should avoid unintended references that keep large objects alive.

Q: What is the difference between shallow and deep copy?

A: A shallow copy duplicates the outer object but shares references to nested objects, so mutating a nested element affects both copies. A deep copy recursively duplicates everything. Use copy.copy for shallow and copy.deepcopy for fully independent nested structures.

import copy
a = [[1, 2], [3]]
b = copy.deepcopy(a)
b[0].append(9)   # a is unchanged

Q: What are *args and **kwargs?

A: *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. They let a function accept a variable number of arguments and are commonly used to forward arguments to another callable.

Q: What is a decorator?

A: A decorator is a callable that takes a function and returns a new function, letting you add behaviour such as logging, timing or caching without editing the original. The @ syntax is sugar for reassigning the name to the wrapped version.

def timer(fn):
    import time
    def wrap(*a, **k):
        t = time.time()
        r = fn(*a, **k)
        print(time.time() - t)
        return r
    return wrap

@timer
def work():
    ...

Q: What is the difference between a generator and a list?

A: A list holds all elements in memory at once; a generator yields items lazily, one at a time, using the yield keyword. Generators are memory efficient for large or infinite sequences and can only be iterated once. Use them when you do not need random access or the full sequence simultaneously.

Q: How do *args differ from a normal list parameter?

A: A normal list parameter expects the caller to pass one list object; *args lets the caller pass many separate positional values that Python packs into a tuple. The choice affects the calling convention, so pick based on how callers should invoke the function.

Q: What does the with statement do?

A: It manages a context, guaranteeing setup and cleanup through a context manager that defines __enter__ and __exit__. It is most used for files and locks because the resource is released even if an exception occurs, removing the need for explicit try or finally blocks.

Q: How do you count word frequency in a string?

A: Use collections.Counter, which builds a frequency mapping in one pass.

from collections import Counter
words = 'to be or to be'.split()
print(Counter(words))
# Counter({'to': 2, 'be': 2, 'or': 1})

Advanced python interview questions

Q: What is the Global Interpreter Lock (GIL)?

A: The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time. It simplifies memory management but prevents CPU-bound threads from running truly in parallel. For CPU-bound work use multiprocessing or native extensions; for I/O-bound work, threads and asyncio still help because the lock is released during I/O.

Q: How does asyncio differ from threading?

A: asyncio uses a single-threaded event loop with cooperative multitasking, switching tasks at await points, which suits many concurrent I/O operations with low overhead. Threading uses OS threads and pre-emptive switching but is limited by the GIL for CPU work. Choose asyncio for high-concurrency network code and threading for blocking libraries.

Q: What is the difference between @staticmethod and @classmethod?

A: A classmethod receives the class as its first argument, conventionally cls, and can access or create class-level state, making it useful for alternative constructors. A staticmethod receives neither self nor cls and is simply a function grouped inside a class for organisation.

Q: How does Python’s method resolution order (MRO) work?

A: Python uses the C3 linearisation algorithm to determine the order in which base classes are searched for a method. You can inspect it with ClassName.__mro__ or the mro() method. It gives a consistent, predictable order for multiple inheritance and is what makes super() cooperative.

Q: What are __slots__ used for?

A: Defining __slots__ replaces the per-instance __dict__ with a fixed set of attributes, reducing memory use and speeding attribute access for classes with many instances. The trade-off is that you cannot add new attributes dynamically and multiple inheritance becomes more constrained.

Q: How would you remove duplicates from a list while keeping order?

A: Use a dict, which preserves insertion order in modern Python, or a set to track seen items.

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

Q: What is the difference between deep-nested comprehension and generator expressions for large data?

A: A comprehension materialises the whole result in memory, which can be costly for large inputs. A generator expression, written with parentheses, produces items lazily and pairs well with functions like sum or any, so prefer it when you only iterate once over a big dataset.

How to prepare for a Python interview

Rehearse the fundamentals out loud — mutability, the GIL, decorators and generators are almost guaranteed. Solve at least forty coding problems on strings, lists and dictionaries, and always state time and space complexity. Keep one small project ready to discuss, and practise explaining your decisions rather than reciting definitions. For related roles, review our Python guide alongside SQL interview questions, and if you are early in your career, our apprenticeship and Skill India guide and the GetJobsNews homepage list current openings worth targeting.

Frequently Asked Questions

How do I prepare for a Python interview?

Revise core data types, mutability, OOP, decorators, generators and the GIL, then practise 40 to 50 coding problems on strings, lists and dictionaries. Build one small project, be ready to explain your code line by line, and rehearse time and space complexity for every solution you write.

Is Python hard to learn for freshers?

No. Python has clean, readable syntax and a huge standard library, so most freshers write useful scripts within weeks. The harder part is depth — mutability, memory, the GIL and async — which interviewers probe. Focus on understanding why code behaves as it does, not just memorising answers.

What Python topics are asked most for freshers?

Freshers get data types, mutable versus immutable objects, list versus tuple, dictionaries, list comprehensions, string handling, functions with default arguments, and simple OOP. Expect two or three live coding tasks such as reversing a string, counting word frequency or removing duplicates while keeping order.

Should I learn a framework before a Python interview?

For core Python roles, master the language first. If the job description names Django, Flask or FastAPI, learn request handling, routing, ORM basics and one project. For data roles, prioritise pandas and NumPy instead. Match your prep to the specific role rather than learning every framework superficially.