Rates TodayNIFTY25,670-0.83%SENSEX83,630.7-0.83%Gold 24K ₹11,320.24/g down186.46Silver ₹134.77/g down2.72
InsightforGeeks

Python interview questions and answers

24 questions · Easy, Medium and Hard

These Python questions cover what interviewers ask most: the built-in types, functions and classes, the features that make Python different (comprehensions, generators, decorators, context managers), and how the language works under the hood.

Each answer is short enough to say in an interview, with a small example where it helps. Run the examples yourself; seeing the output is the fastest way to remember them.

Easy 8Medium 10Hard 6

Easy questions

What is Python, and why is it so popular?

Python is a high-level, interpreted, general-purpose language with a clean, readable syntax. It is popular because it is quick to learn, has a huge standard library and ecosystem, and is used for scripting, web back ends, data analysis, machine learning and automation.

Often asked next: Is Python compiled or interpreted?

What is the difference between mutable and immutable types?

A mutable object can be changed after it is created; an immutable one cannot. Lists, dictionaries and sets are mutable. Integers, floats, strings, tuples and frozensets are immutable. Changing an immutable value creates a new object.

This matters for function arguments and default values: a function that changes a mutable argument changes the caller's object too.

a = [1, 2]
b = a          # the same list
b.append(3)
print(a)       # [1, 2, 3]

s = "hi"
t = s.upper()  # a new string; s is unchanged
print(s, t)    # hi HI

What is the difference between a list and a tuple?

Both hold ordered items, but a list is mutable and a tuple is immutable. Use a list for a collection that changes, and a tuple for a fixed group of values such as a coordinate or a database row. Because tuples are immutable (and hashable if their items are), they can be dictionary keys; lists cannot.

How do dictionaries work?

A dictionary stores key-value pairs and finds a value by its key in about constant time, using a hash table. Keys must be hashable (immutable, such as strings, numbers and tuples of them). Since Python 3.7, dictionaries keep the order in which keys were inserted.

ages = {"Asha": 30, "Ravi": 25}
ages["Meera"] = 28
print(ages.get("Joe", "unknown"))  # unknown
for name, age in ages.items():
    print(name, age)

What is the difference between == and is?

== compares values: do the two objects look equal? is compares identity: are they the very same object in memory? Use == for values and is only for singletons such as None: if x is None.

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

What are *args and **kwargs?

*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. They let a function accept a variable number of arguments, and are common in wrappers and decorators.

def show(*args, **kwargs):
    print(args, kwargs)

show(1, 2, name="Asha")  # (1, 2) {'name': 'Asha'}

What is PEP 8?

PEP 8 is the official style guide for Python code: four spaces for indentation, snake_case for functions and variables, CapWords for classes, lines kept to a reasonable length, and so on. Following it makes code easier for others to read. Tools such as flake8, ruff and black check or apply it automatically.

What is a virtual environment, and why use one?

A virtual environment is an isolated folder with its own Python interpreter and installed packages. It keeps each project's dependencies separate, so installing or upgrading a library for one project cannot break another. Create one with python -m venv .venv, activate it, then install packages with pip.

Python learning hub →

Medium questions

What is a list comprehension, and what is a generator expression?

A list comprehension builds a list in one expression: [x * x for x in nums if x > 0]. A generator expression has the same shape in parentheses, but produces values one at a time instead of building the whole list, so it uses much less memory for large data.

squares = [n * n for n in range(5)]   # [0, 1, 4, 9, 16]
total = sum(n * n for n in range(1_000_000))  # no big list built

What are generators, and what does yield do?

A generator is a function that uses yield to hand back values one at a time and pause, keeping its local state until it is asked for the next one. This makes it possible to work with large or infinite sequences without holding everything in memory.

def count_up(limit):
    n = 1
    while n <= limit:
        yield n
        n += 1

for i in count_up(3):
    print(i)  # 1, 2, 3

What is a decorator?

A decorator is a function that takes a function and returns a new one, usually adding behaviour before or after the original runs, such as logging, timing, caching or access checks. The @name syntax above a function is shorthand for func = name(func). Use functools.wraps so the wrapped function keeps its name and docstring.

import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(func.__name__, time.perf_counter() - start)
        return result
    return wrapper

@timed
def work():
    return sum(range(100000))

What is a context manager, and how does the with statement work?

A context manager sets something up and always cleans it up, even if an error occurs. The with statement calls its __enter__ method on the way in and __exit__ on the way out. Files are the classic example: with open(...) as f closes the file for you. You can write your own with a class, or with the @contextmanager decorator.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello")
# the file is closed here, even after an error

Python learning hub →

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

A shallow copy creates a new container but reuses the same inner objects, so changing a nested object shows up in both copies. A deep copy copies everything recursively, so the copies are fully independent. Use copy.copy() or list.copy() for shallow, and copy.deepcopy() for deep.

import copy

a = [[1, 2], [3]]
b = copy.copy(a)
c = copy.deepcopy(a)
a[0].append(99)
print(b[0])  # [1, 2, 99]  shared with a
print(c[0])  # [1, 2]      independent

Why is a mutable default argument a bug?

Default values are created once, when the function is defined, not each time it is called. If the default is a list or dictionary, every call that uses it shares and changes the same object. Use None as the default and create a fresh object inside the function.

def add(item, items=[]):   # bug: one shared list
    items.append(item)
    return items

print(add(1))  # [1]
print(add(2))  # [1, 2]  surprise

def add_fixed(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

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

An instance method takes self and works on one object. A class method, marked @classmethod, takes cls and works on the class itself; it is often used for alternative constructors. A static method, marked @staticmethod, takes neither; it is just a function that lives in the class for organisation.

How does exception handling work in Python?

Code that might fail goes in try. except catches specific exceptions, else runs only if nothing was raised, and finally always runs, which makes it the place for cleanup. Catch the specific exception you expect, not a bare except:, which also hides bugs and stops Ctrl+C. Raise your own with raise, and define custom exceptions by subclassing Exception.

text = input("Enter a number: ")

try:
    value = int(text)
except ValueError:
    print("Not a number")
else:
    print("Got", value)
finally:
    print("done")

What is the difference between an iterable and an iterator?

An iterable is anything you can loop over, such as a list, string or dictionary; it has an __iter__ method that returns an iterator. An iterator produces the items one at a time with __next__ and raises StopIteration when it runs out. A for loop calls iter() on the iterable and then next() repeatedly.

What does if __name__ == "__main__" do?

Every module has a __name__. When a file is run directly, it is "__main__"; when it is imported, it is the module's name. The check lets a file work both as a script and as a module: the code under it runs only when the file is executed directly, not when it is imported.

Hard questions

What is the GIL, and how does it affect threads?

The Global Interpreter Lock is a lock in the standard CPython interpreter that lets only one thread run Python bytecode at a time. As a result, threads do not speed up CPU-bound Python code on multiple cores. They still help with I/O-bound work, because the lock is released while waiting for the network or disk.

For CPU-bound work, use multiprocessing (separate processes, each with its own interpreter) or native libraries such as NumPy that release the lock. Recent Python versions also have an experimental free-threaded build.

Often asked next: How would you speed up a CPU-heavy script?

When would you use threading, multiprocessing or asyncio?

Use asyncio for many I/O-bound tasks, such as thousands of network requests, using one thread and cooperative async/await. Use threading for I/O-bound work with libraries that are not async. Use multiprocessing (or concurrent.futures.ProcessPoolExecutor) for CPU-bound work, because processes avoid the GIL, at the cost of more memory and the need to pass data between processes.

import asyncio

async def fetch(n):
    await asyncio.sleep(1)
    return n

async def main():
    results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
    print(results)  # takes about 1 second, not 3

asyncio.run(main())

How does memory management and garbage collection work in Python?

CPython uses reference counting: every object tracks how many references point to it, and it is freed as soon as the count reaches zero. Reference counting cannot free objects that reference each other in a cycle, so there is also a cyclic garbage collector that finds and removes such groups periodically.

Memory leaks in Python usually come from references that are kept alive by mistake, such as growing global lists, caches without limits, or lingering callbacks.

What is the method resolution order (MRO)?

With multiple inheritance, Python needs to decide which class's method to use. The MRO is the order in which it searches the classes, computed with the C3 linearisation algorithm so that every class comes before its parents and the order of base classes is respected. You can see it with ClassName.__mro__, and super() follows it.

What are dunder methods, and what is the difference between __str__ and __repr__?

Dunder (double underscore) methods such as __init__, __len__, __eq__ and __add__ let your classes work with Python's built-in operations and functions. __repr__ should return an unambiguous description for developers, ideally something that looks like the code to recreate the object; __str__ returns a readable version for users. If only __repr__ is defined, print uses it too.

What are dataclasses, and why use them?

The @dataclass decorator generates __init__, __repr__ and __eq__ for a class from its annotated fields, so simple data-holding classes need very little code. Options include frozen=True for immutable instances, order=True for sorting, and field(default_factory=list) for mutable defaults.

from dataclasses import dataclass, field

@dataclass
class Order:
    id: int
    items: list[str] = field(default_factory=list)

o = Order(1)
print(o)  # Order(id=1, items=[])

Keep learning

Handy free tools

More interview questions