Interview Questions

10 Common Python Interview Questions and Answers

Author: Interview Questions Posted 16 days ago 39 min read

Preparing for a Python technical interview—or brushing up on your core fundamentals—means understanding not just how to write Python, but why it behaves the way it does under the hood. Here are 10 of the most common Python interview questions, complete with clear explanations and code examples.


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

The primary difference is mutability:

  • Lists are mutable, meaning you can add, remove, or modify elements after creation. They are defined using square brackets [].
  • Tuples are immutable, meaning once created, their contents cannot be changed. They are defined using parentheses ().

Because tuples are immutable, they are slightly faster, consume less memory, and can be used as keys in a dictionary (provided all elements inside the tuple are also immutable).

my_list = [1, 2, 3]
my_list[0] = 99  # Valid

my_tuple = (1, 2, 3)
# my_tuple[0] = 99  # Raises TypeError: 'tuple' object does not support item assignment


2. How is memory managed in Python?

Python manages memory automatically through a combination of reference counting and garbage collection:

  1. Reference Counting: Every object in Python keeps track of how many references point to it. When an object's reference count drops to zero, the memory occupied by the object is immediately deallocated.
  2. Garbage Collection (GC): Reference counting alone cannot handle circular references (e.g., Object A references Object B, and Object B references Object A). Python's cyclic garbage collector periodically detects and cleans up these unreachable reference cycles.

3. What is the Global Interpreter Lock (GIL)?

The Global Interpreter Lock (GIL) is a mutex (lock) in CPython (the standard Python implementation) that allows only one thread to execute Python bytecode at a time, even on multi-core processors.

  • Why it exists: It simplifies memory management in CPython by making reference counting thread-safe without needing fine-grained locks on every single object.
  • Impact: Multi-threaded Python programs are limited to a single CPU core for CPU-bound tasks. However, the GIL is released during I/O-bound operations (like network requests or file reading), making threading still effective for I/O concurrency. For CPU-bound parallelism, developers use the multiprocessing module instead.

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

  • == checks for value equality (do these two objects have the same data?).
  • is checks for reference/identity equality (do these two variables point to the exact same object in memory?).
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True (values are identical)
print(a is b)  # False (different objects in memory)
print(a is c)  # True (c points to the same object as a)


5. What are *args and **kwargs?

*args and **kwargs allow functions to accept a variable number of arguments:

  • *args (Non-Keyword Arguments) collects extra positional arguments into a tuple.
  • **kwargs (Keyword Arguments) collects extra named arguments into a dictionary.

(Note: The names args and kwargs are conventions; the single asterisk * and double asterisks are what actually perform the unpacking.)

def demo_func(*args, **kwargs):
    print("Positional:", args)
    print("Keyword:", kwargs)

demo_func(1, 2, 3, name="Alice", role="Admin")
# Positional: (1, 2, 3)
# Keyword: {'name': 'Alice', 'role': 'Admin'}


6. What is a decorator in Python?

A decorator is a design pattern that allows you to modify or extend the behavior of a function or class without permanently modifying its source code. In Python, functions are first-class objects, meaning they can be passed as arguments and returned from other functions.

def my_decorator(func):
    def wrapper():
        print("Something happens before the function.")
        func()
        print("Something happens after the function.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

For more info about Python decorator, please read How Python Decorators Actually Work (With Step-by-Step Code Examples)


7. What is the difference between a generator and a normal function?

  • A normal function uses return to send back a single value (or collection) and terminates completely, wiping its local state.
  • A generator function uses the yield keyword. Instead of returning all results at once, it pauses execution, yields a single value, and saves its local state so it can resume right where it left off on the next call.

Generators are heavily used for lazy evaluation, allowing you to iterate over massive datasets (like large log files) without loading the entire dataset into RAM.

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

counter = count_up_to(3)
print(next(counter))  # 1
print(next(counter))  # 2


8. Explain shallow copy vs. deep copy.

When copying nested objects (like a list containing other lists), Python offers two approaches via the copy module:

  • Shallow Copy (copy.copy()): Creates a new outer object, but inserts references to the original nested objects. Modifying a nested element affects both the original and the copy.
  • Deep Copy (copy.deepcopy()): Creates a new outer object and recursively copies all nested objects inside it. The original and the copy are completely independent.
import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99

print(shallow[0][0])  # 99 (affected by change)
print(deep[0][0])     # 1  (completely independent)


9. Why are mutable default arguments dangerous in Python?

Default argument values in Python are evaluated only once at the time the function is defined, not each time the function is called. If you use a mutable object (like a list or dict) as a default argument, any modifications made to it will persist across future calls to that function.

The Pitfall:

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

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b'] -> Unexpected!

The Solution: Use None as the default value and initialize the mutable object inside the function body.

def add_item(item, target_list=None):
    if target_list is None:
        target_list = []
    target_list.append(item)
    return target_list


10. What are list comprehensions, and how do they compare to map() and filter()?

A list comprehension provides a concise, readable syntax for creating lists based on existing iterables.

# Squaring even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]

Comparison:

  • List comprehensions are generally preferred in modern Python because they are easier to read and avoid the overhead of calling a lambda function on every element.
  • map() and filter() return iterators (evaluating lazily), whereas a standard list comprehension builds the entire list in memory immediately. (Tip: If you want lazy evaluation with comprehension syntax, use a generator expression by replacing [] with ()).