Python Interview Questions and Answers

Core language, data structures, comprehensions, decorators and async programming.

Practise 10 random 307 peer-reviewed questions
Python Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level Python interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 What is a generator and when should you use one? Medium

A generator is a function that yields values lazily using yield. Calling it returns a generator object that produces items on demand and remembers its position, so memory stays O(1) instead of materialising the whole sequence.

def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.strip()

# process a huge file without loading it all into memory
for line in read_lines('big.log'):
    ...

Use generators for streaming data, pipelines and infinite sequences. They are also the foundation of async, where an async generator yields with async for.

2 Explain decorators with a practical example. Medium

A decorator is a callable that takes a function and returns a new one, adding behaviour without changing the original code. The @decorator syntax is sugar for func = decorator(func).

import functools, 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:.3f}s')
        return result
    return wrapper

@timed
def train():
    ...

Real uses: logging, authentication, caching, retries, rate limiting. functools.wraps preserves the wrapped function's metadata. Decorators with arguments need an extra layer of nesting.

3 What is pickling and unpickling? Medium

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

4 How Python is interpreted? Medium

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

5 How memory is managed in Python? Medium

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

6 What are the tools that help to find bugs or perform static analysis? Medium

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

7 What are Python decorators? Medium

A decorator in Python is a design pattern that dynamically alters or extends the behavior of a function or class without permanently modifying its source code. In Python, decorators are higher-order functions that accept a callable and return an enhanced callable:

### How Decorators Work:

import functools
import time

def timer_decorator(func):
    @functools.wraps(func)  # Preserves function metadata (__name__, __doc__)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        execution_time = time.perf_counter() - start_time
        print(f"[{func.__name__}] executed in {execution_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def process_data(records):
    time.sleep(0.1)
    return len(records)

### Common Production Use Cases:

  1. Authentication & Authorization: @login_required, @roles_allowed(['admin']) in Django and Flask.
  2. Caching / Memoization: @functools.lru_cache(maxsize=128) for expensive computations.
  3. Rate Limiting & Retries: Automatically retrying network requests upon transient failure.
  4. Logging & Metrics Instrumentation: Emitting OpenTelemetry traces or Prometheus metrics around API calls.
8 What is the difference between list and tuple? Medium

Both lists and tuples are ordered sequence collections in Python, but they differ fundamentally in mutability, memory allocation, and intended design use:

| Feature | list | tuple |
| :--- | :--- | :--- |
| Mutability | Mutable (elements can be added, updated, or removed in place) | Immutable (fixed size and contents after creation) |
| Syntax | Square brackets: [1, 2, 3] | Parentheses: (1, 2, 3) |
| Memory Allocation | Over-allocates memory buffer to allow dynamic resizing | Compact, fixed-size contiguous memory block |
| Iteration Performance | Slightly slower iteration and creation overhead | Faster creation and iteration |
| Hashability | Unhashable (cannot be used as dictionary key or set item) | Hashable (can be dictionary key if all elements are hashable) |
| Idiomatic Usage | Homogeneous collections that grow or shrink | Heterogeneous records, fixed coordinate tuples (x, y) |

### Memory Benchmark Example:

import sys
l = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4, 5)
print(sys.getsizeof(l))  # ~104 bytes (due to resizing buffer)
print(sys.getsizeof(t))  # ~80 bytes (exact compact allocation)
9 How are arguments passed by value or by reference? Medium

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

10 What is Dict and List comprehensions are? Medium

List and Dictionary comprehensions provide a concise, declarative syntax to construct new lists and dictionaries from existing iterables:

### 1. List Comprehension:
Syntax: [expression for item in iterable if condition]

# Traditional approach
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x ** 2)

# Comprehension equivalent (faster & cleaner)
squares = [x ** 2 for x in range(10) if x % 2 == 0]
# Result: [0, 4, 16, 36, 64]

### 2. Dictionary Comprehension:
Syntax: {key_expr: value_expr for item in iterable if condition}

users = [("alice", 28), ("bob", 34), ("carol", 22)]
adult_map = {username: age for username, age in users if age >= 25}
# Result: {'alice': 28, 'bob': 34}

### Why Comprehensions Are Preferred:
Comprehensions execute at C-level speed in CPython, bypassing the overhead of repeated Python bytecode LIST_APPEND instructions, while producing readable and expressive code.

11 What are the built-in type does Python provides? Medium

There are mutable and Immutable types of Pythons built in types Mutable built-in types
List Sets
Dictionaries Immutable built-in types
Strings Tuples Numbers

12 What is namespace in Python? Medium

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

13 What is lambda in Python? Medium

A lambda function in Python is a small, anonymous (unnamed) function defined using the lambda keyword:

### Syntax:
lambda arguments: expression

# Simple lambda
multiply = lambda x, y: x * y
print(multiply(4, 5))  # Output: 20

# Practical usage as a sorting key
students = [('Alice', 88), ('Bob', 95), ('Charlie', 78)]
students.sort(key=lambda item: item[1], reverse=True)
# Result: [('Bob', 95), ('Alice', 88), ('Charlie', 78)]

### Key Constraints:

  • A lambda function can accept any number of positional or keyword arguments.
  • It can contain only a single expression, which is automatically evaluated and returned.
  • It cannot contain statements (no return, pass, assert, try/except, or assignments).
  • *PEP 8 Guidance:* Do not assign lambdas to variable names (f = lambda x: x); define a standard def function instead for proper stack trace debugging.
14 Why lambda forms in Python does not have statements? Medium

Python creator Guido van Rossum deliberately designed Python lambda expressions to be restricted to a single expression rather than containing full statements:

### Key Reasons:

  1. Grammar & Indentation Alignment:

Python's syntax relies fundamentally on indentation to delimit statement blocks. Allowing multi-line statements (like if/else, loops, or try/except) inside a lambda expression would introduce syntactic ambiguity when nested inside expressions, parentheses, or argument lists.

  1. Encouraging Clean Code Architecture:

Lambdas were intended strictly for small, disposable inline callbacks (such as passing a key function to sorted() or map()). If a function requires complex statements, exception handling, or multiple lines of logic, defining an explicit named function using def improves readability, allows docstrings, and ensures meaningful function names appear in stack traces.

15 What is pass in Python? Medium

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

16 In Python what are iterators? Medium

An iterator in Python is an object that represents a stream of data. It implements the Python Iterator Protocol, which consists of two core magic methods:

  1. __iter__(): Returns the iterator object itself.
  2. __next__(): Returns the next item from the sequence. When no elements remain, it raises the StopIteration exception.

### Custom Iterator Example:

class CountUpTo:
    def __init__(self, max_value):
        self.max_value = max_value
        self.current = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= self.max_value:
            val = self.current
            self.current += 1
            return val
        raise StopIteration

counter = CountUpTo(3)
for num in counter:
    print(num)  # Prints 1, 2, 3

### Iterable vs Iterator:

  • An Iterable is any object that can return an iterator via iter(obj) (e.g. lists, tuples, dicts, strings).
  • An Iterator is the stateful helper that actually produces values one at a time via next(it).
17 What is unit test in Python? Medium

A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

18 In Python what is slicing? Medium

Slicing is a Python mechanism for extracting a sub-sequence from a sequence data type (such as a list, tuple, or str) using extended indexing notation:

### Syntax:
sequence[start:stop:step]

  • start: Zero-based beginning index (inclusive). Defaults to 0.
  • stop: Ending index (exclusive). Defaults to sequence length.
  • step: Stride / increment value between indices. Defaults to 1.

### Practical Examples:

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(data[2:6])    # [2, 3, 4, 5] (sublist from index 2 to 5)
print(data[:4])     # [0, 1, 2, 3] (first 4 items)
print(data[6:])     # [6, 7, 8, 9] (from index 6 to end)
print(data[::2])    # [0, 2, 4, 6, 8] (every second item)
print(data[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse copy)

Slicing creates a new shallow copy of the requested elements without modifying the original sequence.

19 What are generators in Python? Medium

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let's try and build a generator for fibonacci numbers –

## generate fibonacci numbers upto n

def fib(n):
    p, q = 0, 1
    while(p < n):
        yield p
        p, q = q, p + q

x = fib(10) # create generator object

## iterating using __next__(), for Python2, use next()
x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error

## iterating using loop
for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8

20 What Is Docstring In Python? Medium

A docstring is a unique text that happens to be the first statement in the following Python constructs:

Module, Function, Class, or Method def inition.

A docstring gets added to the __doc__ attribute of the string object.

Showing 20 of 307 questions

Frequently Asked Questions About Python Interviews

What do hiring managers evaluate in Python technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing Python questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.