Skip to content
Tutorials Center
My learning

Topics

Lesson 149 of 149 ยท Practice and Review

Python Interview Questions

38 common Python interview questions with concise answers, from lists vs tuples and scope to generators, decorators, the GIL, memory and metaclasses.

Python interviews tend to test two things: whether you know how the language behaves, and whether you can explain it clearly. This page collects 38 questions that come up again and again, grouped by level and topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson and review it. A few questions ask you to read code and predict its output; run those editors only after you've made your guess.

Tip: in a real interview, a short correct answer plus a tiny example beats a long recital. Mention trade-offs ("this is faster, but uses more memory") whenever you can: that's what separates mid-level answers from junior ones.

Junior level

Language basics

What kind of language is Python?

Python is a high-level, general-purpose language that is dynamically typed (types belong to values, not variable names, and are checked while the program runs) and strongly typed (it won't silently convert "3" + 4; it raises a TypeError). The standard implementation, CPython, compiles source code to bytecode and runs it on a virtual machine, which is why Python is usually called interpreted. It supports procedural, object-oriented and functional styles.

What is the difference between a list and a tuple?

Both are ordered sequences that allow duplicates and any types. A list is mutable: you can add, remove and change items. A tuple is immutable, so it's hashable when its items are, which means it can be a dictionary key or a set member. Use tuples for fixed records like coordinates or return values, and lists for collections that change. Tuples are also slightly smaller and faster to create. See Tuples.

Which built-in types are mutable, and which are immutable?

Immutable: int, float, bool, str, tuple, frozenset, bytes and None. Mutable: list, dict, set, bytearray and most user-defined objects. "Changing" an immutable value, such as s += "!", actually creates a new object and rebinds the name. This matters when objects are shared: every name that refers to a mutable object sees its changes.

What is the difference between == and is?

== compares values (it calls __eq__). is compares identity: whether both names refer to the very same object in memory. Use is only for singletons such as None (if result is None:). Results like 256 is 256 being True come from CPython caching small integers, an implementation detail you should never rely on. See Membership and Identity.

What are truthy and falsy values?

In a condition, every object counts as true or false. Falsy values are False, None, zero of any numeric type, and empty containers or strings: "", [], {}, set(), range(0). Everything else is truthy by default. Classes can control this with __bool__ or __len__. That's why if items: is the idiomatic way to check that a list isn't empty.

What do *args and **kwargs mean?

In a function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. The names are just conventions; the stars matter. In a call, the same stars do the reverse and unpack: f(*values, **options). A bare * in the parameter list makes the following parameters keyword-only, and / makes the preceding ones positional-only. See Arguments.

What does if __name__ == "__main__": do?

Every module has a __name__. When a file is run directly, its __name__ is "__main__"; when it's imported, __name__ is the module's name. Code under this check runs only when the file is executed as a script, so the same file can be imported for its functions without starting the program or its demo code. See Modules.

Scope, functions and errors

How does Python decide which variable a name refers to?

It searches four scopes in order, known as LEGB: Local (the current function), Enclosing (outer functions), Global (the module), and Built-in. Assigning to a name inside a function makes it local for the whole function, unless you declare it global (module level) or nonlocal (an enclosing function). Reading an outer variable needs no declaration. See Scope.

What is a list comprehension, and when should you avoid one?

A comprehension builds a list from an iterable in one expression: [n * n for n in nums if n > 0]. It's usually clearer and a bit faster than an equivalent append() loop. Avoid it when the logic needs several conditions or nested loops that hurt readability, when you only need side effects (use a loop), or when the data is large and you only iterate once (use a generator expression in parentheses instead). See List Comprehensions.

How do try, except, else and finally work together?

Code that might fail goes in try. Each except handles one or more specific exception types. else runs only if try raised nothing, which keeps the protected block small. finally always runs, error or not, and is used for cleanup (though a with statement is usually better for that). Catch the narrowest exception you can handle. See Exceptions.

Code reading: identity and equality

What does this print? Decide before you run it.

Python Identity versus equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Explain the output of the identity and equality example.

It prints False True False and then [1, 2, 3, 4]. b = a doesn't copy anything: both names point to one list, so appending through b changes a. After that, a and c no longer have equal values, and c was always a different object.

Mid level

Data and copying

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

A shallow copy (list.copy(), dict.copy(), copy.copy(), items[:]) creates a new outer container but keeps references to the same inner objects. A deep copy (copy.deepcopy()) recursively copies the inner objects too. With nested data, changing an inner list through a shallow copy also changes the original. Deep copies are slower and use more memory, so use them only when you need full independence.

Why is a mutable default argument a problem?

Default values are evaluated once, when the def statement runs, not on each call. A default like items=[] is therefore one list shared by every call that doesn't pass its own, so data leaks between calls. The fix is items=None and if items is None: items = [] inside the function. See Arguments.

Code reading: a class attribute

Python Who is on the team?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why does the red team list both Ana and Ben?

members is a class attribute, created once and shared by all instances. self.members.append() finds it on the class and mutates that single list. The fix is to create per-instance state in __init__: self.members = []. See Classes.

Iteration and functions

What is the difference between an iterable and an iterator?

An iterable is anything you can loop over; it has __iter__ and returns a fresh iterator each time (lists, strings, dicts). An iterator produces values one at a time with __next__, raises StopIteration when done, and remembers its position, so it can be consumed only once. iter(iterable) gets an iterator and next(iterator) takes one value; a for loop does both for you. See Iterators.

What is a generator, and why use one?

A generator is a function containing yield. Calling it returns an iterator that runs the body lazily, pausing at each yield and resuming on the next request. Generators produce values on demand instead of building a full list, so they use constant memory, can represent infinite sequences and can be chained into pipelines. Generator expressions, (x * 2 for x in data), are the inline form. See Generators.

Code reading: a generator used twice

Python Summing twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why is the second sum 0?

The first line prints 14 (0 + 1 + 4 + 9) and the second prints 0. A generator expression is an iterator: the first sum() consumes all its values, so the second finds nothing left and returns the sum of an empty sequence. Use a list if you need to iterate more than once, or recreate the generator.

What is a decorator?

A decorator is a callable that takes a function (or class) and returns a replacement, usually a wrapper that adds behavior before or after the original runs: logging, timing, caching, access checks. @timer above def f is shorthand for f = timer(f). A good decorator uses functools.wraps so the wrapper keeps the original's name and docstring. Built-in examples are @property, @staticmethod, @classmethod and @functools.cache. See Decorators.

What is a context manager?

An object used with with that sets something up on entry and reliably cleans it up on exit, even if an exception happens. It implements __enter__ and __exit__, or you write one as a generator decorated with contextlib.contextmanager. Files, locks, database transactions and temporary settings are typical uses. See Context Managers.

Object-oriented Python

What is the difference between an instance method, a class method and a static method?

An instance method receives the instance as self and works with its data. A class method (@classmethod) receives the class as cls; it's commonly used for alternative constructors such as Date.from_string(), and it works correctly with subclasses. A static method (@staticmethod) receives neither; it's a plain function placed in the class namespace because it belongs there logically. See Methods.

What is the difference between __str__ and __repr__?

__repr__ gives an unambiguous, developer-facing representation, ideally one that looks like code to recreate the object: Point(x=1, y=2). __str__ gives a friendly, user-facing text and is used by print() and str(). If only __repr__ is defined, str() falls back to it, so define __repr__ first. See Special Methods.

What does @property do?

It turns a method into an attribute-style accessor. You can start with a plain attribute and later add validation or a computed value without changing callers: account.balance keeps working. Add a @balance.setter for writes; without one, the attribute is read-only. See Properties.

How do inheritance and super() work, and what is the MRO?

A subclass inherits attributes and methods from its base classes and can override them. super() returns a proxy that calls the next class in the method resolution order (MRO), not simply "the parent". With multiple inheritance, Python computes the MRO with the C3 linearization algorithm; you can inspect it with ClassName.__mro__. Cooperative classes all call super() so each class in the chain runs once. See Inheritance.

What is duck typing?

"If it walks like a duck and quacks like a duck, it's a duck": code relies on what an object can do, not on its declared type. A function that calls .read() works with files, io.StringIO and any object that has a read() method. Type checkers express this with typing.Protocol. The trade-off is that mistakes show up at runtime unless you add type hints and a checker. See Abstract Classes and Protocols.

Tooling

Are type hints enforced at runtime?

No. Annotations like def f(x: int) -> str are stored as metadata and ignored by the interpreter, so f("oops") still runs. Their value comes from static type checkers (mypy, Pyright), editors and documentation. Libraries such as Pydantic can read hints to validate data at runtime, but that's opt-in. See Type Hints.

What is a virtual environment, and why use one?

A virtual environment is an isolated folder with its own interpreter link and installed packages. Each project gets the exact dependency versions it needs without conflicting with other projects or the system Python. Create one with python -m venv .venv, activate it, install with pip, and record dependencies in a file such as requirements.txt or pyproject.toml. See Virtual Environments.

How do you test Python code?

With the built-in unittest module or, more commonly, pytest, which uses plain assert statements and fixtures. Good tests follow arrange-act-assert, test one behavior each, cover edge cases and error paths, and replace slow or external dependencies with fakes or unittest.mock. Running them in CI keeps the codebase safe to change. See Testing.

Senior level

Concurrency and performance

What is the GIL?

The Global Interpreter Lock in CPython lets only one thread execute Python bytecode at a time. It simplifies memory management and keeps single-threaded code fast, but it means threads don't speed up CPU-bound Python code. Threads still help with I/O-bound work, because the GIL is released while waiting on I/O, and many C extensions (such as NumPy) release it during heavy computation. Since Python 3.13 there is an optional free-threaded build without the GIL, which is officially supported from 3.14 but still not the default. See Concurrency.

When would you choose threads, processes or asyncio?
  • asyncio: many concurrent I/O tasks (network calls, sockets) in one thread with cooperative await points; very scalable, but it needs async-aware libraries.
  • Threads: I/O-bound work with ordinary blocking libraries, or a few background tasks. concurrent.futures.ThreadPoolExecutor is the simple API.
  • Processes: CPU-bound work that needs multiple cores. Each process has its own interpreter and GIL, at the cost of startup time and data serialization (ProcessPoolExecutor, multiprocessing).

See asyncio and Concurrency.

How would you find and fix a slow piece of Python code?

Measure first: profile with cProfile (or a sampling profiler) to find the hot spots, and benchmark candidate fixes with timeit. Then, in rough order of impact: choose a better algorithm or data structure (a set instead of list lookups, a dict index instead of nested loops), avoid repeated work (caching with functools.cache), push loops into C (built-ins, comprehensions, NumPy), and process data lazily with generators. Only then consider concurrency or compiled extensions. See Performance and Algorithms.

Memory and internals

How does Python manage memory?

CPython uses reference counting: each object tracks how many references point to it and is freed as soon as the count reaches zero. Reference cycles (objects pointing at each other) can't reach zero, so a cyclic garbage collector (gc module) periodically finds and frees unreachable cycles. weakref creates references that don't keep objects alive, which is useful for caches. Memory freed by small objects is usually kept in Python's own allocator pools for reuse. See Memory Management.

What does __slots__ do?

Declaring __slots__ = ("x", "y") in a class replaces the per-instance __dict__ with fixed storage for the listed attributes. Instances use noticeably less memory and attribute access is slightly faster, which matters when you create millions of objects. The trade-off: you can't add attributes that aren't listed, and multiple inheritance with slots needs care. @dataclass(slots=True) generates them for you. See Metaclasses, Descriptors and Object Internals.

What is a descriptor?

A descriptor is an object stored as a class attribute that defines __get__, and optionally __set__ or __delete__, to control what happens when that attribute is accessed on instances. It's the mechanism behind property, methods (functions are descriptors that bind self), classmethod and staticmethod. Write your own for reusable attribute logic, such as a validated field used by many classes. See Metaclasses, Descriptors and Object Internals.

What is a metaclass, and when would you use one?

Classes are objects too, and a metaclass is the class of a class: type by default. A custom metaclass can customize class creation, for example registering subclasses or validating class attributes. They're rarely needed: class decorators and __init_subclass__ solve most of the same problems more simply, so prefer those. Metaclasses mostly appear inside frameworks such as ORMs. See Metaclasses, Descriptors and Object Internals.

What is the relationship between __eq__ and __hash__?

Objects that compare equal must have the same hash, or dictionaries and sets break. That's why defining __eq__ in a class sets __hash__ to None, making instances unhashable, unless you also define __hash__. Base the hash on the same immutable fields used for equality, typically hash((self.x, self.y)). Mutable objects whose equality can change shouldn't be hashable at all. A frozen data class handles all of this for you.

Closures and error handling

What is a closure?

A closure is an inner function that remembers variables from the enclosing function's scope even after that function has returned. It's how decorators keep a reference to the wrapped function and how factories like make_multiplier(3) produce customized functions. Use nonlocal to reassign a captured variable. Closures capture variables, not values, which leads to the classic late-binding surprise below.

Code reading: late binding

Python Three little lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why does the first list contain the same number three times?

The first line prints [20, 20, 20]. Each lambda looks up i when it's called, and by then the loop has finished with i == 2. The second version binds the current value as a default argument, which is evaluated at definition time, so it prints [0, 10, 20]. functools.partial is another fix.

Why are bare except: and broad except Exception: risky?

A bare except: also catches KeyboardInterrupt and SystemExit, so a program can't even be stopped cleanly. except Exception: is safer but still hides bugs such as TypeError and NameError behind a generic message. Catch the specific exceptions you can handle, log unexpected ones with the traceback, and re-raise with raise NewError(...) from error to keep the original cause. Broad handlers belong only at the very top of a program, such as a request handler that logs and returns a 500 error. See Custom Exceptions and Logging and Warnings.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does print(bool([]), bool([0])) print?

    An empty list is falsy, but a list containing one item is truthy, even if that item is 0.
  2. 2. Which statement about the GIL is accurate?

    Threads still overlap during I/O, processes each have their own GIL, and the free-threaded build is optional.
  3. 3. You define __eq__ in a class but not __hash__. What happens?

    Python sets hash to None so that equal objects can't end up with different hashes.

Summary

  • Junior questions check the basics: types and mutability, == vs is, truthiness, scope, arguments and exceptions.
  • Mid-level questions focus on copying, iterators and generators, decorators, context managers and object-oriented design.
  • Senior questions go under the hood: the GIL and concurrency choices, profiling, memory management, __slots__, descriptors, metaclasses and the hash/equality contract.
  • Explaining an idea clearly, with a small example and its trade-offs, is the skill that interviews reward.

You've reached the end of the Python course. Keep practicing with the exercises, keep the cheat sheet handy, and come back to the Python course overview whenever you want to review a topic. Happy coding!