Skip to content

Top Python Interview Questions and Answers

Updated 13 min read Aimerscrew

Whether you're applying for your first developer job or an internship, you'll almost certainly face Python interview questions. The good news: interviewers ask about the same core ideas again and again. This page collects 35 of the most common questions, from beginner to intermediate, each with a short answer you can say out loud and a tiny code example that proves it.

🌍 Real-life example

Think of a driving test. The examiner doesn't ask you to recite the whole highway code; they check a handful of things that show you really understand the road: mirrors, signals, parking. A Python interview works the same way. A few classic questions, like "list or tuple?" or "what does a decorator do?", reveal whether you truly understand the language.

How should you prepare for a Python interview?

Don't memorize answers word for word. Interviewers usually follow up with "why?" or "show me", so make sure you can explain each idea in your own words and type a small example. For every question below:

  1. Read the answer, then close the page and explain it out loud.
  2. Run the code example yourself and change it a little.
  3. Follow the link to the full lesson if anything feels shaky.
Diagram comparing a shallow copy, where the new outer list still points to the same inner lists as the original, with a deep copy, where the inner lists are copied too
A favorite interview topic: a shallow copy shares the inner objects, a deep copy duplicates them.

Basic Python interview questions

1. What is Python?

Python is a high-level, general-purpose programming language known for its readable syntax. It is interpreted, dynamically typed and supports several styles of programming: procedural, object-oriented and functional. It is used for web development, data science, automation, AI and much more. See introduction to Python.

2. Is Python compiled or interpreted?

Both, in a way. The standard interpreter, CPython, first compiles your source code into bytecode (the .pyc files you may see in __pycache__), and then the Python Virtual Machine interprets that bytecode line by line. Because you never run a separate compile step yourself, Python is usually called an interpreted language. More in how Python runs code.

3. What does "dynamically typed" mean?

You don't declare a variable's type. Python works out the type from the value at run time, and the same name can later point to a value of a different type.

item = 42
print(type(item))
item = "forty-two"
print(type(item))
<class 'int'>
<class 'str'>

4. What is PEP 8?

PEP 8 is Python's official style guide. It recommends things like four-space indentation, snake_case names for variables and functions, CapWords for classes and lines of reasonable length. Following it makes your code look familiar to every Python developer.

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

== checks whether two values are equal. is checks whether two names point to the same object in memory.

cart_a = ["milk", "eggs"]
cart_b = ["milk", "eggs"]
cart_c = cart_a

print(cart_a == cart_b)
print(cart_a is cart_b)
print(cart_a is cart_c)
True
False
True

Use is only for identity checks, most often if value is None. See identity and membership operators.

6. What are Python's main built-in data types?

Numbers (int, float, complex), text (str), booleans (bool), sequences (list, tuple, range), sets (set, frozenset), mappings (dict) and the special value None. See Python data types.

7. What is the difference between / and //?

/ is true division and always returns a float. // is floor division: it rounds the result down to the nearest whole number.

print(7 / 2)
print(7 // 2)
print(-7 // 2)
3.5
3
-4

Note the last line: floor division rounds toward negative infinity, so -3.5 becomes -4, not -3.

8. What do break, continue and pass do?

break exits the loop completely, continue skips to the next iteration, and pass does nothing at all; it's a placeholder where Python requires a statement. See break, continue and pass.

Data types and data structures questions

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

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.

scores = [10, 20]
scores[0] = 99
print(scores)

name = "sam"
name[0] = "S"
[99, 20]
TypeError: 'str' object does not support item assignment

Full explanation in mutable vs immutable.

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

ListTuple
Syntax[1, 2, 3](1, 2, 3)
Mutable?YesNo
Can be a dict key?NoYes (if its items are hashable)
Typical useA collection that grows or changesA fixed record, like coordinates

Tuples are also slightly smaller in memory. See list vs tuple vs set vs dict.

11. What is a set and when would you use one?

A set is an unordered collection of unique items. Use it to remove duplicates, to test membership quickly, or to compare groups.

monday = {"Ana", "Ben", "Chen"}
tuesday = {"Ben", "Dev"}
print(sorted(monday | tuesday))
print(monday & tuesday)
['Ana', 'Ben', 'Chen', 'Dev']
{'Ben'}

12. What can be used as a dictionary key?

Any hashable object, which in practice means immutable ones: strings, numbers, tuples of immutable items. Lists and dictionaries can't be keys because they can change.

seats = {("row", 5): "Ali"}
print(seats[("row", 5)])

bad = {["row", 5]: "Ali"}
Ali
TypeError: unhashable type: 'list'

13. What is a list comprehension?

A short way to build a list from another iterable, optionally filtering items, in one readable line.

prices = [4.5, 12.0, 8.25, 20.0]
cheap = [p for p in prices if p < 10]
print(cheap)
[4.5, 8.25]

There are also dict and set comprehensions. See list comprehension.

14. How do you reverse a string or a list?

Slicing with a step of -1 returns a reversed copy. Lists also have an in-place .reverse() method.

print("python"[::-1])
print([1, 2, 3][::-1])
nohtyp
[3, 2, 1]

Function interview questions

15. What are *args and **kwargs?

*args collects any extra positional arguments into a tuple. **kwargs collects any extra keyword arguments into a dictionary. The names are a convention; the stars do the work.

def order(*items, **options):
    print(items)
    print(options)

order("latte", "muffin", size="large", to_go=True)
('latte', 'muffin')
{'size': 'large', 'to_go': True}

See *args and **kwargs.

16. What is a lambda function?

A small, anonymous function written in one expression. It's handy as a short argument to functions like sorted().

players = [("Kim", 320), ("Lou", 450), ("Ana", 280)]
print(sorted(players, key=lambda p: p[1], reverse=True))
[('Lou', 450), ('Kim', 320), ('Ana', 280)]

If the logic needs more than one expression, write a normal def function. See lambda functions.

17. What is the LEGB rule?

It's the order Python searches for a name: Local (inside the current function), Enclosing (outer functions), Global (the module) and Built-in (names like print and len). The first match wins. See variable scope.

level = "global"

def outer():
    level = "enclosing"
    def inner():
        print(level)
    inner()

outer()
enclosing

18. What do global and nonlocal do?

By default, assigning to a name inside a function creates a local variable. global tells Python the name refers to the module-level variable; nonlocal points it at the variable in the nearest enclosing function.

visits = 0

def record_visit():
    global visits
    visits += 1

record_visit()
record_visit()
print(visits)
2

19. Why is a mutable default argument dangerous?

Default values are created once, when the function is defined, not on every call. A mutable default like a list is shared between calls.

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

print(add_item("apple"))
print(add_item("bread"))
['apple']
['apple', 'bread']

The fix is to use None as the default and create the list inside: if cart is None: cart = [].

20. What does a function return if it has no return statement?

It returns None. The same happens with a bare return. See the return statement.

Object-oriented programming questions

21. What are __init__ and self?

__init__ is the method Python calls automatically right after creating a new object, so you can set its starting attributes. self is the first parameter of every instance method and refers to the object the method is working on.

class Flight:
    def __init__(self, number, seats):
        self.number = number
        self.seats = seats

f = Flight("BA117", 180)
print(f.number, f.seats)
BA117 180

See __init__ and self.

22. What is the difference between class and instance attributes?

A class attribute is defined in the class body and shared by all objects. An instance attribute is set on self and belongs to one object.

class Player:
    team = "Tigers"
    def __init__(self, name):
        self.name = name

a, b = Player("Raj"), Player("Eve")
print(a.team, b.team, a.name, b.name)
Tigers Tigers Raj Eve

23. What are dunder (magic) methods?

Methods with double underscores on both sides, like __init__, __str__, __len__ and __eq__. Python calls them for you behind the scenes, so your objects can work with built-in syntax such as print(), len() and ==.

class Playlist:
    def __init__(self, songs):
        self.songs = songs
    def __len__(self):
        return len(self.songs)

print(len(Playlist(["Halo", "Yellow", "Clocks"])))
3

See magic methods.

24. What is the difference between __str__ and __repr__?

__str__ gives a friendly, readable description for users (used by print()). __repr__ gives an unambiguous, developer-focused description, ideally one that looks like code to recreate the object. If only __repr__ is defined, Python uses it for both.

25. What is inheritance and what does super() do?

Inheritance lets a child class reuse and extend a parent class. super() calls a method from the parent, most often its __init__.

class Account:
    def __init__(self, owner):
        self.owner = owner

class SavingsAccount(Account):
    def __init__(self, owner, rate):
        super().__init__(owner)
        self.rate = rate

s = SavingsAccount("Noor", 0.04)
print(s.owner, s.rate)
Noor 0.04

See inheritance.

26. What is the difference between @classmethod and @staticmethod?

A class method receives the class as its first argument (cls) and is often used as an alternative constructor. A static method receives neither the class nor the object; it's a plain function that lives inside the class for organization. See class and static methods.

27. What is a dataclass?

A class decorated with @dataclass from the dataclasses module. Python writes __init__, __repr__ and __eq__ for you based on the annotated fields.

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

print(Product("Mug", 9.5))
print(Product("Mug", 9.5) == Product("Mug", 9.5))
Product(name='Mug', price=9.5)
True

See dataclasses.

Intermediate Python interview questions

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

A shallow copy creates a new outer object but keeps references to the same inner objects. A deep copy recursively copies everything, so nothing is shared (see the diagram above).

import copy

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

grid[0][0] = 99
print(shallow)
print(deep)
[[99, 2], [3, 4]]
[[1, 2], [3, 4]]

See shallow vs deep copy.

29. How does exception handling work in Python?

Put risky code in try. If an error happens, the matching except block runs. else runs only if no error happened, and finally always runs, which makes it ideal for cleanup.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
    else:
        print("Result:", result)
    finally:
        print("Done")

safe_divide(10, 4)
safe_divide(1, 0)
Result: 2.5
Done
Cannot divide by zero
Done

See try-except.

30. What does the with statement do?

It uses a context manager to set something up and guarantee it is cleaned up afterwards, even if an error occurs. The classic example is a file that closes itself automatically: with open("notes.txt") as f:. See the with statement and context managers.

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

An iterable is anything you can loop over, such as a list or string. An iterator is the object that actually produces the values one at a time with next() and remembers where it is. Calling iter() on an iterable gives you an iterator.

it = iter(["red", "green"])
print(next(it))
print(next(it))
print(next(it))
red
green
StopIteration

See iterators.

32. What is a generator?

A function that uses yield instead of return. Each yield hands back one value and pauses the function until the next value is requested. Generators produce values lazily, so they use very little memory even for huge sequences.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))
[3, 2, 1]

See generators.

33. What is a decorator?

A function that takes another function and returns a new function that adds behavior around it, without changing the original code. The @name line above a function is shorthand for func = name(func).

def shout(func):
    def wrapper(name):
        return func(name).upper() + "!"
    return wrapper

@shout
def greet(name):
    return f"hello, {name}"

print(greet("maya"))
HELLO, MAYA!

See decorators.

34. What is the GIL?

The Global Interpreter Lock is a lock in CPython that lets only one thread run Python bytecode at a time. As a result, threads don't speed up CPU-heavy work such as number crunching, but they still help with I/O-heavy work such as downloading files, because the lock is released while a thread waits. For CPU-heavy parallel work, developers typically use multiple processes (the multiprocessing module) instead. Python 3.13 introduced an optional "free-threaded" build without the GIL, but the standard build still has it.

35. What does if __name__ == "__main__": mean?

Every module has a __name__ variable. When you run a file directly, it's set to "__main__"; when the file is imported, it's set to the module's name. Code under this check runs only when the file is executed directly, not when it's imported. See creating modules.

Common mistakes in Python interviews

1. Giving textbook answers you can't explain

If you say "tuples are immutable", be ready to show what happens when you try to change one. Short examples beat long definitions.

2. Saying is and == are the same

They sometimes give the same result by coincidence, especially with small numbers, but they answer different questions. Always explain "equal value" vs "same object".

3. Overstating the GIL

Don't say "Python can't do parallelism". Threads still help with waiting on networks and files, and multiple processes run truly in parallel.

4. Coding in silence

In live coding rounds, talk through your thinking. Interviewers care about how you reason, not just whether the final answer is perfect.

Practice exercise

🏋️ Try it yourself

A common live-coding question: write a function first_unique(text) that returns the first character that appears only once in a string, or None if there isn't one. Test it with "swiss", "level" and "aabb".

Show solution
def first_unique(text):
    counts = {}
    for char in text:
        counts[char] = counts.get(char, 0) + 1
    for char in text:
        if counts[char] == 1:
            return char
    return None

print(first_unique("swiss"))
print(first_unique("level"))
print(first_unique("aabb"))
w
v
None

Counting first and then scanning again keeps the solution simple and fast: two passes over the string instead of checking every character against every other one.

What's next?

You've reviewed the theory and practiced the questions interviewers love. Finish the tutorial with the Python cheat sheet, a one-page quick reference you can keep open while you code. Want more hands-on practice first? Try the Python exercises for beginners.

Key takeaways

  • Mutable objects (lists, dicts, sets) can change in place; immutable ones (ints, strings, tuples) cannot.
  • Use == to compare values and is to check whether two names point to the same object, such as x is None.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • A decorator wraps a function to add behavior; a generator uses yield to produce values lazily.
  • A shallow copy shares inner objects with the original; a deep copy duplicates everything.
  • The GIL lets only one thread run Python bytecode at a time in CPython, which limits CPU-bound threads but not I/O-bound ones.
  • Explain answers in your own words and back them up with a tiny code example.

Frequently asked questions

What is the difference between a list and a tuple in Python?

A list is mutable, so you can add, remove and change items, and it is written with square brackets. A tuple is immutable, written with parentheses, and can be used as a dictionary key. Use tuples for fixed records and lists for collections that change.

What is the difference between is and == in Python?

The == operator checks whether two values are equal. The is operator checks whether two names refer to the exact same object in memory. Two separate lists with the same items are equal but are not the same object.

What are *args and **kwargs in Python?

They let a function accept any number of arguments. *args gathers extra positional arguments into a tuple, and **kwargs gathers extra keyword arguments into a dictionary.

What is a decorator in Python?

A decorator is a function that takes another function and returns a new one that adds behavior before or after it, such as logging or timing. You apply it by writing @decorator_name above the function definition.

What is the GIL in Python?

The Global Interpreter Lock is a mechanism in CPython that allows only one thread to execute Python bytecode at a time. It limits speedups from threads for CPU-heavy tasks, but threads still help with I/O-heavy tasks, and multiprocessing can run code in parallel.

How do I prepare for a Python interview?

Review core topics such as data types, mutability, functions, scope, OOP basics, exceptions, comprehensions, generators and decorators. Practice explaining each one out loud with a small example, and solve a few short coding problems every day.