Python Interview Questions 2026: 52 Questions With Answers
Python interview questions in 2026 test more than syntax. Interviewers probe decorators, generators, the GIL, async patterns, and the standard-library quirks that separate the candidate who scripted in Python from the engineer who understands it. This guide covers 50+ questions across data structures, OOP, async, and tricky concepts, plus the new-grad-specific prep plan.
By Sam K., Founder, InterviewChamp.AI · Last updated
28 min readTL;DR: Python interviews in 2026 cluster into seven buckets: data structures, OOP, decorators, generators, async and the GIL, standard-library idioms, and algorithm patterns written the Python way. For a CS new grad, the offer hinges less on hard algorithms and more on idiom fluency plus the concepts coursework skips (the GIL, decorators, generators), so knowing 20 concepts at moderate depth beats knowing 5 deeply. With only a weekend, drill decorators and collections.Counter first, because they show up at almost every round.
Quick map: the Python interview topics on this page#
Below is the full list, grouped the way interviewers tend to group it. Each row points to a numbered block of practice questions further down.
| Topic | What it covers | Questions |
|---|---|---|
| Data structures | lists, tuples, dicts, sets, hashing, complexity | Q1 to Q10 |
| OOP | inheritance, MRO, method types, dunder methods | Q11 to Q18 |
| Decorators | writing them, functools.wraps, decorators with arguments | Q19 to Q23 |
| Generators and iterators | yield, lazy evaluation, itertools | Q24 to Q28 |
| Async and concurrency | the GIL, threads vs processes vs asyncio | Q29 to Q34 |
| Standard library | Counter, defaultdict, lru_cache, deque, chain | Q35 to Q39 |
| Algorithms in Python | two-sum, palindromes, sliding window, heaps | Q40 to Q47 |
| Pandas and NumPy | Series vs DataFrame, filtering, merges, axes | Q48 to Q52 |
If you're short on time, read the next three sections first. They explain what the questions are checking, and that changes how you should answer every one of them.
What Python interview questions test in 2026#
Interviewers check three things, in this order. First, can you write idiomatic Python, not just code that happens to run? Second, do you understand the language's quirks below the level of syntax? Third, can you talk through your reasoning while someone watches? Syntax is the floor, and almost every CS new grad clears it. The idiom check and the deep-language check are where most interviews are won or lost.
The bar has moved in the 2026 hiring market. As of the 2025-2026 hiring cycle, Python is the dominant language for backend, data engineering, machine learning, DevOps, and analytics roles. So more interviewers read Python every day, and more of them know what good Python looks like. Picture a candidate who creates an empty list and appends inside a loop when a comprehension would do the job. That used to read as "fine, just verbose." Now it reads as someone who used Python without ever learning it. The bar is fluency, not literacy.
Here's a rough split of question types new-grad candidates report seeing in their loops:
- 30-40% data structures (lists, tuples, sets, dicts, time complexity)
- 20% object-oriented programming (classes, inheritance, dunder methods)
- 20% algorithm patterns implemented in Python
- 15% language-specific concepts (decorators, generators, GIL, async)
- 5-10% standard-library fluency (collections, itertools, functools)
That 15% language-specific slice is the one most people underprepare for. It's also the slice that decides the outcome far more often than its size suggests.
How Python interview questions differ from general coding interviews#
Any coding interview, in any language, tests algorithm fluency, how you break a problem down, and how you communicate. A Python interview piles a fourth thing on top: fluency with the language's own idioms and concepts. Three of those come up again and again in 2026 Python interviews, and you rarely see them in rounds held in other languages.
Decorators. A decorator is a callable that takes a function and returns a function, usually one that wraps the original with extra behavior. Python treats them as a first-class idea in a way Java and C++ don't. Nearly every Python codebase uses them (@property, @staticmethod, @classmethod, @functools.lru_cache, plus the framework ones in Flask or FastAPI). Interviewers expect you to know how they work inside, not just where to put the @.
Generators and the yield keyword. A generator is a function with at least one yield that produces values lazily instead of building them all in memory at once. Lazy evaluation sits at the base of idiomatic Python, and it matters most for roles that touch large datasets. Say a candidate writes range(1_000_000) and assumes it builds a list. It doesn't, because range in Python 3 is lazy. That candidate isn't the one a team wants debugging a streaming pipeline.
The GIL. The GIL (Global Interpreter Lock) is a mutex inside the reference Python interpreter that lets only one thread run Python bytecode at a time, which is why CPU-bound threaded code doesn't speed up. It's a polarizing topic, and it still gets asked at almost every Python interview above the most-junior tier. "What is the GIL and how does it affect threading?" is one of the questions candidates search for most, and for a reason. Interviewers use it as a litmus test: does this person understand why their threaded code didn't get faster?
Three more concepts round out the Python-only surface area:
- context managers (
withblocks) - dunder methods, the special methods that make your class behave like a built-in
- the standard library, especially
collections,itertools, andfunctools
The standard library one is the quickest win. A candidate who reaches for collections.Counter instead of hand-building a counter dict shows in two seconds what takes other candidates two minutes to prove.
Here's a typical path for the new grad we built this guide for. 487 applications since May 2025, 14 phone screens, zero offers, 11 months in, 600 LeetCode problems solved. Strong on patterns, weak on Python idioms, because most of that LeetCode grind happened in Java. One stuck OA from a Series B fintech on Monday morning, in Python this time, on HackerRank. A Meta phone screen that went sideways 8 minutes in, when the interviewer asked about the GIL. The engineer was nice tho. This candidate doesn't need more LeetCode. They need decorators, collections.Counter, and the GIL story drilled tight enough to recite half-asleep at 9am on Monday.
Interview questions in Python programming: which version to answer for#
Answer for the Python version the job post names, or the current stable release (check python.org for which one that is). The examples on this page assume Python 3.14.
Most interview questions in Python programming don't depend on the version at all. A dict lookup is O(1) average in every release you'll be asked about. Still, a handful of answers changed recently, and an interviewer who keeps up will notice if yours is two releases out of date.
Four 3.14 changes deserve one sentence each in your head. All of them are listed on the official What's New in Python 3.14 page:
- Free-threaded Python is officially supported (PEP 779). It's an optional build, and the default one still has the GIL. That's the new "second half" of the GIL answer.
- Annotations are evaluated lazily (PEP 649 and PEP 749). Forward references in type hints mostly stop needing quotes.
- Template string literals (PEP 750). A
t"..."prefix gives you a template object instead of a finished string, so a library can escape the values before it builds SQL or HTML. exceptwithout brackets (PEP 758). You can now writeexcept ValueError, TypeError:to catch several exception types.
Nobody will ask you to recite PEP numbers. What you might hear is "anything new in recent Python you've used?" Naming one of these, with a line on why it matters, is a good answer. "I haven't moved to 3.14 yet, but the free-threaded build is the one I'm watching" also works fine. It shows you know it exists.
The 50+ Python interview questions you should rehearse#
The set below covers the seven categories that show up most, plus a short pandas and NumPy block for data roles. Each question comes with an answer outline. These aren't scripts to memorize word for word. They're the bones of what a strong answer covers, and you should put them in your own words. The structure is the part that carries the weight.
Python data structures interview questions (10 Q)
What's the difference between a list and a tuple?
Show sample answerHide answerSay yours out loud first, then check.
A list is mutable and a tuple is immutable. Tuples are hashable, so they can be dict keys or set members, and they're slightly faster to allocate. Reach for a tuple when the data is a record with a fixed shape. Reach for a list when it's a sequence that can grow or shrink.
How does a dict work under the hood?
Show sample answerHide answerSay yours out loud first, then check.
A dict is a hash table. Each key gets hashed with hash(key), and that hash picks the bucket. Collisions are handled with open addressing. Lookup, insert, and delete run in O(1) on average and O(n) in the worst case. Since Python 3.7, insertion order is a language guarantee for dicts.
What is the time complexity of common list operations?
Show sample answerHide answerSay yours out loud first, then check.
Index access and append are O(1). Popping from the end is O(1) too. Popping from the front, or inserting at index 0, is O(n), because every other element has to shift over. A membership test (x in lst) is O(n). When you need O(1) pops from the front, switch to collections.deque.
What is the time complexity of common dict and set operations?
Show sample answerHide answerSay yours out loud first, then check.
Insert, lookup, delete, and membership tests are all O(1) on average for both. Iterating is O(n). Under the hood, a set is close to a dict with keys and no values.
What is a hashable object in Python?
Show sample answerHide answerSay yours out loud first, then check.
An object is hashable when it has a __hash__ method that returns a consistent integer, plus an __eq__ that respects the hash contract: equal objects must have equal hashes. Immutable built-ins whose contents are also hashable can be hashed: ints, floats, strings, frozensets, and tuples of hashables. Lists, dicts, and sets aren't. Custom classes are hashable by default, using object identity, unless you override __eq__ without also overriding __hash__.
How do you reverse a list in Python?
Show sample answerHide answerSay yours out loud first, then check.
There are three idiomatic ways. lst.reverse() flips the list in place. lst[::-1] hands back a new reversed list. reversed(lst) gives you a lazy iterator. Choose by what you need: .reverse() to change the original, the slice for a fresh copy, and reversed() when you only plan to loop over it.
What's the difference between is and ==?
Show sample answerHide answerSay yours out loud first, then check.
== calls __eq__ and checks whether two values are equal. is checks identity, meaning whether two names point at the same object in memory. So a == b can be true while a is b is false. The rule: use is for None and other singletons, and == for comparing values. The classic gotcha is that CPython caches small integers (-5 to 256), so is can seem to work on them by accident. Never rely on that.
How do you merge two dicts in Python?
Show sample answerHide answerSay yours out loud first, then check.
In Python 3.9 and later, use the | operator: merged = a | b. On older versions, write {**a, **b}. To merge in place, call a.update(b). If a key appears in both, the right-hand side wins.
What does dict.get(key, default) do that dict[key] doesn't?
Show sample answerHide answerSay yours out loud first, then check.
dict[key] raises KeyError when the key is missing. dict.get(key, default) returns the default instead, or None if you didn't give one. The follow-up interviewers like is "when should you use defaultdict instead?" The answer: when you plan to mutate the default, like appending to a list or bumping a counter. get returns the default without storing it in the dict, while defaultdict creates the default and stores it.
How do you remove duplicates from a list while preserving order?
Show sample answerHide answerSay yours out loud first, then check.
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]
Or, in Python 3.7+, just write list(dict.fromkeys(lst)). Both run in O(n) and keep the original insertion order.
Python OOP interview questions (8 Q)
How does inheritance work in Python?
Show sample answerHide answerSay yours out loud first, then check.
A class inherits from one or more parents by listing them in parentheses, as in class Dog(Animal):. The subclass picks up every method and attribute of the parent. To override something, redefine it. To call the parent's version, use super().method(). Python allows multiple inheritance, and the lookup order is the MRO (Method Resolution Order), which comes from the C3 linearization algorithm.
What is the MRO?
Show sample answerHide answerSay yours out loud first, then check.
The Method Resolution Order is the sequence Python walks when it looks up a method on a class that has more than one parent. C3 linearization computes it, and it guarantees an ordering that stays consistent with each parent's own MRO. To see it, print ClassName.__mro__ or call ClassName.mro(). The case interviewers care about is the diamond problem. When class D inherits from B and C, and both of those inherit from A, the MRO is D, then B, then C, then A, and super() follows that same order.
How do classmethod, staticmethod, and a plain instance method differ?
Show sample answerHide answerSay yours out loud first, then check.
An instance method gets self as its first argument and works on one instance. A classmethod gets cls and works on the class itself, which makes it handy for alternative constructors like from_string or from_dict. A staticmethod gets nothing extra. It's an ordinary function that lives in the class's namespace, used when the logic belongs with the class but doesn't need the instance or the class.
What is the @property decorator?
Show sample answerHide answerSay yours out loud first, then check.
@property turns a method into a read-only attribute. You write obj.price instead of obj.price(), but the method body still runs on every access. Add a setter with @price.setter if it needs to be writable. The typical use is a computed attribute, like area built from width * height, without changing how callers access it.
What's the difference between __init__ and __new__?
Show sample answerHide answerSay yours out loud first, then check.
__new__ allocates the new instance and returns it. __init__ sets up that already-allocated instance. In ordinary classes you only touch __init__. You override __new__ when you subclass an immutable type (int, str, tuple), build a singleton, or write a metaclass. __new__ is a static method that receives cls, and __init__ is an instance method that receives self.
What are dunder methods? Name five.
Show sample answerHide answerSay yours out loud first, then check.
Dunder methods are Python's special methods, the ones Python calls for you during built-in operations. Five common ones:
__init__for initialization__repr__for a developer-readable representation__str__for a user-readable string__len__, which makeslen(obj)work__eq__, which makes==work
Others worth knowing: __hash__, __iter__, __next__, __getitem__, __setitem__, __enter__, __exit__, __call__.
How do you make a class iterable?
Show sample answerHide answerSay yours out loud first, then check.
Define __iter__ so it returns an iterator, meaning an object with __next__. Or write __iter__ as a generator using yield. The iterator's __next__ returns the next value, or raises StopIteration when there's nothing left. For most classes the generator route is cleaner, since Python tracks the iterator state for you.
What is duck typing?
Show sample answerHide answerSay yours out loud first, then check.
It's the idea that whether an object fits an operation depends on the methods it has, not on its type. A function that calls obj.read() works on any object with a read method, no matter what it inherits from. Python prefers duck typing over explicit type checks. With type hints (PEP 544 Protocols), you can type-check duck types statically and still keep the runtime flexibility.
Python decorators interview questions (5 Q)
What is a decorator?
Show sample answerHide answerSay yours out loud first, then check.
A callable that takes a function and returns a function. Putting @decorator above a definition is just sugar for f = decorator(f). Ones you'll see all the time: @property, @staticmethod, @classmethod, @functools.lru_cache, and the framework decorators in Flask, FastAPI, and Django.
Write a decorator that logs the execution time of a function.
Show sample answerHide answerSay yours out loud first, then check.
import functools, time
def timer(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:.4f}s")
return result
return wrapper
The @functools.wraps line is the detail that matters most here. It keeps the wrapped function's __name__, __doc__, and other metadata. Leave it out and wrapper.__name__ comes back as "wrapper", which breaks introspection and makes debugging a pain.
What does functools.wraps do?
Show sample answerHide answerSay yours out loud first, then check.
It copies the wrapped function's metadata (__name__, __doc__, __module__, __qualname__, __annotations__) over to the wrapper. Without it, the decorated function looks like the wrapper to anything that inspects it, so help(), IDE tooling, and any code reading __name__ all break. Use it every time.
How do you write a decorator that takes arguments?
Show sample answerHide answerSay yours out loud first, then check.
You need three levels of nesting. The outer function takes the decorator's arguments, the middle one takes the function being decorated, and the inner one is the real wrapper.
import functools
def repeat(n):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet():
print("hi")
This is the most common follow-up in decorator questions. Get the three-level shape into your fingers.
What's the difference between a function decorator and a class decorator?
Show sample answerHide answerSay yours out loud first, then check.
They follow the same pattern: take a callable, return a callable. A class decorator just wraps a class instead of a function. It's useful for adding methods, changing attributes, or registering the class somewhere. The decorator itself can also be a class that implements __call__ instead of a nested function, which is often the cleaner choice when the decorator has to keep state.
Python generators + iterators interview questions (5 Q)
What's the difference between yield and return?
Show sample answerHide answerSay yours out loud first, then check.
return ends the function and hands back a value. yield hands back a value, pauses the function, and remembers where it stopped, so the next call picks up from that spot. Any function with at least one yield is a generator function. Calling it returns a generator object, and the body doesn't run until you iterate over it.
What's the memory difference between a list comprehension and a generator expression?
Show sample answerHide answerSay yours out loud first, then check.
The list comprehension [x*2 for x in range(10**6)] builds the whole list in memory, about 8 MB for the list's pointers alone with a million ints. The generator expression (x*2 for x in range(10**6)) builds a lazy iterator that uses constant memory and computes each value only when asked. With large datasets or infinite sequences, that's the difference between a clean loop and an out-of-memory crash.
How do you write a generator that yields the Fibonacci sequence?
Show sample answerHide answerSay yours out loud first, then check.
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
It's an infinite generator with constant memory. To grab the first 10 values without trying to exhaust it, use itertools.islice(fib(), 10).
What is the difference between an iterator and an iterable?
Show sample answerHide answerSay yours out loud first, then check.
An iterable is anything you can loop over. It has an __iter__ method that returns an iterator. An iterator has both __iter__, which returns itself, and __next__, which returns the next value or raises StopIteration. Lists, tuples, dicts, sets, and strings are iterables but not iterators. Generators are both.
What does itertools give you that built-in iteration doesn't?
Show sample answerHide answerSay yours out loud first, then check.
A toolbox of lazy building blocks for iterators:
chainjoins iterables end to endislicetakes a slice without building a listgroupbygroups consecutive equal valuesproductgives Cartesian productscombinationsandpermutationshandle combinatoricsaccumulateproduces running totals
What the interviewer is watching for is whether you reach for itertools when the obvious solution would build a throwaway intermediate list.
Python async / concurrency interview questions (6 Q)
What is the GIL and why does it exist?
Show sample answerHide answerSay yours out loud first, then check.
The Global Interpreter Lock is a mutex inside CPython that lets only one thread execute Python bytecode at a time. It exists because CPython's memory management relies on reference counting that isn't thread-safe, and a single lock is the simplest way to keep those counts correct. The price is that CPU-bound multithreaded code doesn't speed up. The upside is fast single-threaded code and C extensions that can rely on the GIL instead of their own locking.
The story has a second half now. PEP 703 added an experimental free-threaded build in 3.13, and Python 3.14 made free-threaded Python officially supported under PEP 779. The default build still has the GIL, though. A strong answer covers both halves: the free-threaded build exists and is supported, and you'd check that your C extensions support it before switching.
When should you use threading vs multiprocessing vs asyncio?
Show sample answerHide answerSay yours out loud first, then check.
- threading: I/O-bound work at low-to-moderate concurrency (a few dozen threads). The GIL is released during I/O, so threads do help here.
- multiprocessing: CPU-bound work. Separate processes, separate interpreters, separate GILs, which gives you true parallelism.
- asyncio: I/O-bound work at high concurrency (thousands of connections). Cooperative scheduling on a single thread skips the overhead of switching between threads.
What is a coroutine?
Show sample answerHide answerSay yours out loud first, then check.
A coroutine is a function declared with async def. Calling it gives you a coroutine object that does nothing until something awaits it. Inside a coroutine, await suspends execution until an awaitable (another coroutine, a future, a task) finishes. Coroutines are the basic building block of asyncio.
How does asyncio.gather work?
Show sample answerHide answerSay yours out loud first, then check.
asyncio.gather(coro1, coro2, ...) runs several coroutines concurrently and returns a list of their results. It's the standard way to fan out parallel I/O. If one coroutine raises, the others keep running, but gather re-raises that exception. For finer control, use asyncio.TaskGroup, added in Python 3.11.
What's a common mistake with asyncio?
Show sample answerHide answerSay yours out loud first, then check.
Calling an ordinary blocking function inside an async def. That blocking call freezes the whole event loop until it returns, which kills the point of async. The fix is asyncio.to_thread(blocking_func, args) (Python 3.9+), which pushes the blocking function onto a thread pool while the event loop keeps going. A deeper version of the same mistake is mixing time.sleep (blocking) with asyncio.sleep (awaitable) in one code path.
How would you parallelize a CPU-bound task in Python?
Show sample answerHide answerSay yours out loud first, then check.
Use multiprocessing.Pool or concurrent.futures.ProcessPoolExecutor. Each process gets its own interpreter, which sidesteps the GIL. What you pay is the cost of talking between processes, since data has to be pickled and shipped across. For sub-millisecond tasks, that overhead is bigger than the speedup. For tasks that take 100ms or more, parallelism wins. NumPy-heavy work is a special case: much of the C code underneath releases the GIL, so threading can help there too.
Python standard-library tricky questions (5 Q)
What does collections.Counter do?
Show sample answerHide answerSay yours out loud first, then check.
It's a dict subclass built for counting hashable elements. Counter(['a', 'b', 'a']) returns Counter({'a': 2, 'b': 1}). The methods worth knowing:
.most_common(n)returns the n highest counts as a list of tuples+adds two counters and-subtracts them&keeps the minimum per key (intersection)|keeps the maximum per key (union)
The signal is simple. When a problem says "count the frequency of X," reach for Counter.
What's the difference between dict and collections.defaultdict?
Show sample answerHide answerSay yours out loud first, then check.
defaultdict(factory) creates a default value with the factory function whenever you access a missing key. So d = defaultdict(list); d['key'].append(1) works without first writing d['key'] = []. The factory can be list, int, set, or any callable that takes no arguments. The trap: touching a missing key creates and stores the default, which can hide bugs in code that never meant to insert anything.
What is functools.lru_cache?
Show sample answerHide answerSay yours out loud first, then check.
A decorator that memoizes a function. It caches the return value for each combination of inputs, so a repeat call gets the cached answer instead of recomputing it. @lru_cache(maxsize=128) keeps the 128 most recent results, and maxsize=None means no limit. Wrap any pure function that's expensive to compute (recursive Fibonacci is the classic example) and you get an exponential speedup for free. A newer option: @functools.cache (Python 3.9+) does the same thing with unlimited size.
What's the difference between collections.deque and a list?
Show sample answerHide answerSay yours out loud first, then check.
A deque (double-ended queue) supports O(1) append and pop at both ends. A list gives you O(1) only on the right end, and O(n) on the left. Pick a deque when you need a queue or a sliding window. It also takes a maxlen parameter that drops the oldest items once it's full, which makes it a perfect ring buffer.
When would you use itertools.chain vs the + operator?
Show sample answerHide answerSay yours out loud first, then check.
+ builds a brand-new list, costing O(n+m) time and memory. itertools.chain returns a lazy iterator that uses constant memory until you consume it. For large lists, or when you only need to loop once, chain is the right call.
Python algorithm interview questions (8 Q)
These are the algorithm patterns most often asked with Python idioms in mind. Strong candidates write in the language's own style. Weak ones write Java-in-Python.
Two-sum. Use a hash map for O(n) lookup.
Show sample answerHide answerSay yours out loud first, then check.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
Notice the enumerate, not range(len(nums)), and the dict lookup instead of a nested loop.
Reverse a string. s[::-1] is the one-line answer. The usual follow-up is how you'd do it in place on a list, and the answer there is a two-pointer swap.
Check if a string is a palindrome. For the simple case, s == s[::-1]. When you have to ignore case and non-alphanumeric characters, clean the string first:
Show sample answerHide answerSay yours out loud first, then check.
import re
def is_palindrome(s):
cleaned = re.sub(r'[^a-z0-9]', '', s.lower())
return cleaned == cleaned[::-1]
Find the longest substring without repeating characters. A sliding window, with a set or a dict that tracks the last index where each character showed up.
Detect a cycle in a linked list. Floyd's tortoise-and-hare. Two pointers, one moving twice as fast as the other. If they ever meet, there's a cycle.
Binary search. import bisect gives you the built-in version. Most interviewers want you to write it from scratch, so only reach for bisect if they say it's allowed. Know both the lower-bound and upper-bound variants cold.
K-th largest element. The one-liner is heapq.nlargest(k, nums)[-1]. The deeper version is building a min-heap of size k yourself, which runs in O(n log k) time and O(k) space.
Merge two sorted lists. Walk two pointers and build the result. With generators, heapq.merge(a, b) gives you a lazy version that works on iterables of any length.
Pandas / NumPy interview questions (5 Q)
This block is for data engineer and data analyst roles. For the rest of that loop, pair it with the data engineer interview questions guide.
What's the difference between a pandas Series and a DataFrame?
Show sample answerHide answerSay yours out loud first, then check.
A Series is a 1D labeled array, like one column. A DataFrame is a 2D labeled structure, like a whole table. One handy way to picture it: a DataFrame is a dict of Series that all share one index.
How do you filter rows in a DataFrame?
Show sample answerHide answerSay yours out loud first, then check.
Use boolean indexing: df[df['col'] > 5]. For more than one condition, write df[(df['a'] > 5) & (df['b'] < 10)]. Use & and |, not and and or, and wrap each condition in parentheses.
What's the difference between merge and join in pandas?
Show sample answerHide answerSay yours out loud first, then check.
merge joins on column values, SQL-style. join joins on the index by default. merge is the more flexible one, since you can pick left, right, inner, or outer and join on several keys. join is handy when your indexes are already set.
How is NumPy faster than a Python list?
Show sample answerHide answerSay yours out loud first, then check.
NumPy stores data in contiguous arrays allocated in C with a single dtype, runs vectorized operations in C, and uses SIMD where it's available. A pure Python loop over a million ints is roughly 10-100x slower than the matching vectorized NumPy operation. The trade-off is that every element has to share one dtype.
What does axis=0 vs axis=1 mean in pandas?
Show sample answerHide answerSay yours out loud first, then check.
axis=0 works down the rows, giving column-wise reductions. axis=1 works across the columns, giving row-wise reductions. An easy way to remember it: axis=0 collapses rows, axis=1 collapses columns. So df.mean(axis=0) gives you one mean per column.
How to prepare for a Python interview (6 steps)#
This is a focused three-week plan for a CS new grad whose Python is already conversational but who hasn't drilled the language-specific concepts yet. Shift it around if you're starting from a different spot.
-
Week 1: drill the seven language-specific concepts. Decorators, generators, context managers, the GIL, dunder methods, MRO, and duck typing. Give each one 60-90 minutes, and write at least one example from scratch. Read the official documentation rather than third-party blog posts, because the docs are what interviewers reference.
-
Week 2: solve 40-50 algorithm problems using Python idioms. Pick a curated list (Blind 75 or NeetCode 150) and solve it in idiomatic Python. Reach for
enumerate,zip, comprehensions,collections.Counter,defaultdict, andheapqwhenever they fit. Time yourself: 20 minutes per Medium, 35 per Hard. -
Week 2, alongside step 2: memorize complexity for the four core data structures. That's lists, tuples, dicts, and sets. Put the whole table on one page. Practice saying it out loud while you code, so the answer just comes out when an interviewer asks.
-
Week 3: practice OOP questions. Inheritance, MRO, classmethod vs staticmethod vs instance method,
@property,__init__vs__new__, and dunder methods. Build a small class hierarchy and try each concept on it. -
Week 3: run 3 timed mock interviews. Do them end to end, 45 minutes each, using the core questions from this guide. Narrate your reasoning out loud as you code, since silent coding is a known anti-pattern in live rounds. If you want a live partner that asks follow-ups and grades your idiom fluency in real time, run a practice Python round in a free demo so the GIL answer comes out in your own voice, not a memorized one, when it counts.
-
Morning of the interview: warm up with your cheat sheet. Spend five minutes reviewing the top 20 idioms with their complexity. Writing the sheet from memory was the real prep. The sheet itself is just the warm-up.
Python interview format by role type#
The language is the same, but the way it gets tested changes with the role. Here's how the five most common roles that ask Python interviews in 2026 break down:
| Role | Algorithm depth | OOP depth | Async / GIL focus | Standard library | Pandas / NumPy | Domain extras |
|---|---|---|---|---|---|---|
| Software Engineer (SWE) | High (Blind 75 bar) | Medium | Medium | Medium | Low | Web framework (Flask / FastAPI / Django) |
| Data Engineer | Medium (SQL-heavy) | Low | Medium-High (async pipelines) | High | High | SQL, Spark, distributed systems |
| Data Scientist | Low | Low | Low | Medium | High | Statistics, ML model design |
| DevOps / SRE | Medium | Low | High (process management) | High (subprocess, logging) | None | Linux, Docker, networking |
| ML Engineer | Medium | Medium | High (data parallelism) | Medium | High | PyTorch / TensorFlow, model serving |
Two patterns stand out. First, every role tests the standard library at moderate depth, since collections, itertools, and functools are universal. Second, async and GIL questions pile up in the roles where multi-process or multi-threaded code is the daily work: data engineering, DevOps, and ML engineering. If you're going for a SWE role at a web-heavy company, you can push the GIL deep-dive down the list and spend that time on OOP and framework knowledge.
Python interview cheat sheet#
Here's a one-page reference of the top 20 idioms, laid out for the morning-of warm-up. Writing it from memory is the prep. Having it with you before the interview is the safety net.
| # | Idiom | Use case | Complexity |
|---|---|---|---|
| 1 | enumerate(lst) | Loop with index | O(n) |
| 2 | zip(a, b) | Parallel iteration | O(min(len(a), len(b))) |
| 3 | [x for x in lst if cond] | Filter and transform | O(n) |
| 4 | (x for x in lst) | Lazy iterator | O(1) per yield |
| 5 | dict.get(k, default) | Safe lookup | O(1) avg |
| 6 | collections.defaultdict(list) | Auto-init values | O(1) avg |
| 7 | collections.Counter(lst) | Frequency count | O(n) |
| 8 | collections.deque() | O(1) both-ends queue | O(1) push/pop |
| 9 | heapq.heappush / heappop | Min-heap operations | O(log n) |
| 10 | heapq.nlargest(k, lst) | Top-k elements | O(n log k) |
| 11 | sorted(lst, key=lambda x: x[1]) | Custom sort | O(n log n) |
| 12 | lst.sort(key=..., reverse=True) | In-place sort | O(n log n) |
| 13 | set(lst) | Dedupe, O(1) membership | O(n) build |
| 14 | s[::-1] | Reverse string or list | O(n) |
| 15 | ' '.join(parts) | Concatenate strings | O(n) |
| 16 | f"{var} is {x}" | String interpolation | O(n) in the output length |
| 17 | itertools.chain(a, b) | Lazy concatenation | O(1) per yield |
| 18 | functools.lru_cache | Memoize pure function | O(1) per cache hit |
| 19 | bisect.bisect_left(lst, x) | Binary search in sorted | O(log n) |
| 20 | with open(path) as f: | Auto-close resource | O(1) overhead |
Memorize the top half. The bottom half is polish.
How to handle Python tricky questions you've never seen#
When a Python question catches you cold, reason through it out loud: say what you know, say what you'd guess, then test the guess. You will hit at least one of these. It might be an odd behavior, a built-in method you've never used, or an edge case buried in the standard library. The candidate who freezes loses the round. The one who reasons out loud often passes even with the wrong final answer.
Here's a four-step pattern for unfamiliar questions.
1. Restate the question in your own words. Slow down and confirm what's being asked. Half the "tricky" questions turn normal once you say them back. For example: "So you're asking what happens when I subclass int and override __add__. Would that change how 1 + 2 behaves? Let me think about that." That one sentence buys you about 10 seconds of thinking time, and it shows careful reasoning.
2. Say what you know and what you don't. Don't bluff. "I know __add__ is called for +, but I'm not 100% sure whether subclassing int overrides the operator at the C level or only at the Python level." Calibration beats confidence. Interviewers reward honest uncertainty more than they punish a wrong guess.
3. Reason from first principles. If you can't remember the answer, work it out. "Operators in Python dispatch to dunder methods. If my subclass defines __add__, instances of my subclass should use it. But 1 + 2 uses int.__add__ directly, so my subclass wouldn't affect it." That trail of reasoning is exactly what the interviewer is grading.
4. Test the hypothesis if you can. Asking "can I open a REPL and check?" is welcome in some rounds and not in others. If it's allowed, do it. If it's not, walk through the logic on the whiteboard or in the editor with comments.
This works because tricky Python questions are rarely about memorization. They're about whether you get the model underneath: operator dispatch, MRO, the gap between __new__ and __init__, what a with block compiles to. Your out-loud reasoning is the evidence. Practicing it out loud on prompts you haven't seen is how a frozen round turns into a passing one; see what unlimited mock rounds cost if you want the reps before the real thing.
Common Python interview mistakes for CS new grads#
These are seven common mistakes in new-grad Python interviews.
Writing Java-in-Python. Writing for i in range(len(arr)): print(arr[i]) when for x in arr: print(x) does the job. Starting an empty list and appending in a loop instead of using a comprehension. Hand-rolling a counter dict instead of using collections.Counter. What the interviewer sees is a candidate who used Python but never learned it.
Confusing is and ==. Comparing strings or integers with is. It works some of the time, thanks to small-integer caching, and fails the rest of the time. That's the mark of someone who has hit the gotcha without understanding why it happens.
Not knowing what range does in Python 3. range(10**6) is lazy and uses constant memory. If you treat it like a list (say, you subscript it and assume a full list exists behind it), you're still working from a Python 2 mental model.
Mutable default arguments. def f(x=[]) is the textbook gotcha. That default list gets created once, when the function is defined, and every call shares it. The fix interviewers expect: use None as the sentinel and build the list inside the function.
Bare except: clauses. A bare except: also catches KeyboardInterrupt and SystemExit, which you almost never want to swallow. Always catch a specific exception type, or at minimum except Exception:.
Not preserving function metadata in decorators. Skip functools.wraps and your decorated function loses its __name__, __doc__, and __qualname__. The interviewer is checking whether you've shipped a decorator in a real codebase or only seen one in a tutorial.
Forgetting that dicts are insertion-ordered in 3.7+. Some candidates still think dict iteration order is unspecified. Since Python 3.7 it's a language guarantee. Knowing this is a small signal that you've kept up with the language.
One thing I'd add from watching new grads do this: don't try to memorize all seven the night before. Pick the two that match how you've been writing Python in coursework (almost always Java-in-Python and bare except), then audit your last LeetCode solutions for those two patterns. Fix them until they're muscle memory. The other five tend to take care of themselves once those two are gone.
Key terms#
GIL (Global Interpreter Lock): The mutex inside CPython that lets only one thread execute Python bytecode at a time. It's why multithreaded CPU-bound code in CPython doesn't get faster with more threads, and why you reach for multiprocessing or compiled extensions instead.
Decorator: A callable that wraps a function (or class) to add behavior such as logging, caching, timing, or registration. The @decorator syntax is sugar for f = decorator(f). Almost every Python framework leans on them heavily.
Generator vs iterator: A generator is a function with yield that produces values lazily, and calling it returns a generator object. An iterator is any object with __iter__ and __next__ methods. Every generator is an iterator. Not every iterator is a generator, since you can write an iterator class by hand.
Context manager and the with statement: An object with __enter__ and __exit__ methods that handles setup and teardown of a resource. The with statement guarantees __exit__ runs, even when an exception is raised. It's the standard pattern for files, locks, database connections, and anything else with a lifecycle.
MRO (Method Resolution Order): The order Python searches parent classes when it looks up a method on a class with multiple inheritance. It's computed by the C3 linearization algorithm, and ClassName.__mro__ shows it. It decides how super() resolves in diamond-shaped hierarchies.
Duck typing: The idea that an object's fit for an operation depends on the methods it has, not on the type it inherits from. "If it walks like a duck and quacks like a duck, it's a duck." It's Python's default stance, and Protocols (PEP 544) make it statically type-checkable.
Mutable vs immutable: A mutable object can change after it's created (lists, dicts, sets). An immutable one can't (ints, floats, strings, tuples, frozensets). Built-in mutable containers (lists, dicts, sets) are not hashable, and only hashable objects can be dict keys or set members. The most common source of beginner bugs is assuming a list is shared by value when it's shared by reference.
Related guides#
- Technical phone screen tactics: what to expect in the round that tests these Python concepts under live observation.
- System design basics for new grads: the next round after the Python coding screen at most large employers.
- HackerRank tech interview guide: the platform most likely to host your Python OA.
- CoderPad live coding interview: the platform most likely to host your Python live round.
- Mock interview practice: how to drill these questions under realistic timing pressure.
- LeetCode assessments tech interview guide: the algorithm-pattern depth most Python interviews expect.
About the author: Sam K. is the founder of InterviewChamp.AI, building AI interview prep for the new-grad CS market and writing about the modern interview gauntlet from the inside.
Originally published on InterviewChamp.AI
Related guides
AI Interview Tools 2026: A Buyer's Guide for CS New Grads
The phrase "AI interview" means three different things in 2026 and most candidates land on the wrong page for their actual problem. It can mean a candidate using AI to help during an interview, an employer using AI to score candidates without a human in the room, or an AI bot that runs an entire mock interview for prep. This guide untangles all three, walks through the seven decision criteria that matter when picking a candidate-side AI tool, covers what interviewers can actually detect in 2026, and lays out a $1,847-budget allocation a real CS new grad can copy. Honest-prep voice. No "100% undetectable" claims. No competitor names.
Sam K. ·
Read more →CoderPad Alternatives 2026: 6 Tools — Platform Swap or Candidate Help?
CoderPad is the live-coding interview platform that recruiters and hiring managers use to run human-led technical rounds in 2026. Most people searching for CoderPad alternatives are doing one of two things: an employer shopping for a different platform to run interviews on, or a candidate looking for help with a CoderPad round they have coming up. This guide covers both. Six tools compared honestly, with InterviewChamp positioned as the candidate-side helper for practice and, where the company allows it, for live coding rounds on any platform, not just CoderPad.
Sam K. ·
Read more →InterviewAI Alternatives in 2026: 7 Tools Compared (Mock Practice + Live Interview Copilots)
InterviewAI is the umbrella name people search when they want an AI mock interviewer, an AI that scores async video answers, or a real-time interview helper that surfaces answers during a live round. Three different products live under that one phrase, and the searcher usually wants one of them but lands on a page about the other two. This guide untangles the category, ranks the 7 alternatives most CS new grads actually compare in 2026 (split into mock-practice tools and live-interview copilots), names the price points and ToS posture on each, and gives a one-page decision tree by avatar so Jordan-types stop wasting weekends on the wrong product.
Sam K. ·
Read more →Frequently asked questions
- What Python interview questions should I prepare for in 2026?
- Prepare across seven categories: data structures (lists, tuples, sets, dicts and their time complexity), object-oriented programming (classes, inheritance, MRO, dunder methods), decorators, generators and iterators, async and concurrency (the GIL, asyncio, threading, multiprocessing), standard-library idioms (collections, itertools, functools), and algorithm patterns with Python-specific idioms. Most new-grad Python interviews cover 30-40% data structures, 20% OOP, 20% algorithms, and the remaining 20% on language-specific concepts where the GIL, decorators, and generators get the most attention.
- What's the difference between a list and a tuple in Python?
- A list is mutable and a tuple is immutable. Lists use square brackets and support append, extend, pop, and slice assignment; tuples use parentheses and are fixed at creation. Tuples can be used as dictionary keys and set members because they are hashable; lists cannot. Tuples are also slightly faster to create and iterate over because the interpreter can allocate a single contiguous block. The interview-relevant takeaway is that immutability is the design intent of tuples. They signal that the data is a record, not a sequence.
- What is the GIL in Python?
- The GIL (Global Interpreter Lock) is a mutex inside CPython (the reference Python interpreter) that allows only one thread to execute Python bytecode at a time. It exists because CPython's memory management is not thread-safe, and the GIL is the simplest way to keep reference counts consistent across threads. The practical consequence is that CPU-bound Python code does not get faster on multiple threads. For CPU-bound parallelism you reach for multiprocessing or compiled extensions; for I/O-bound concurrency, threading and asyncio both work because they release the GIL while waiting on I/O. PEP 703 added an experimental free-threaded build in 3.13, and Python 3.14 made that build officially supported (PEP 779). It is still a separate, optional build: the default CPython download keeps the GIL, so that is what most production code runs on in 2026.
- What is a Python decorator?
- A decorator is a callable that takes a function and returns a function. Typically a new function that wraps the original with extra behavior. Decorators are syntactic sugar for the pattern `f = decorator(f)`, applied with the @ symbol above the function definition. Common uses include logging, caching, access control, and timing. The deeper interview question is usually about preserving the wrapped function's metadata using `functools.wraps`, writing a decorator that accepts arguments (which requires three levels of nesting), and understanding that class methods can also be decorated.
- What is the difference between yield and return in Python?
- `return` exits the function and returns a value; `yield` pauses the function, returns a value to the caller, and remembers where it stopped so it can resume on the next call. A function with at least one `yield` is a generator function. Calling it returns a generator object rather than running the body. The generator only runs when iterated. The memory implication is the headline: a list comprehension materializes every element in memory; a generator expression streams them one at a time. For large datasets, generators are the difference between an out-of-memory crash and a clean iteration.
- How does Python's garbage collection work?
- CPython uses reference counting as the primary mechanism. Each object tracks how many references point to it, and when the count drops to zero the object is immediately deallocated. A generational garbage collector runs on top of that to catch reference cycles, which reference counting alone cannot reclaim (two objects pointing at each other). The interview-relevant nuance is that you can break a cycle manually by setting one reference to None, or by using weak references via the `weakref` module. The `gc` module exposes the collector for inspection and tuning.
- What is the difference between asyncio, threading, and multiprocessing?
- All three handle concurrency but solve different problems. `threading` runs multiple threads in a single process and shares memory; useful for I/O-bound work but limited by the GIL for CPU-bound work. `multiprocessing` spawns separate processes with separate memory; useful for CPU-bound parallelism because each process has its own interpreter and its own GIL. `asyncio` runs a single thread with cooperative coroutines; useful for high-concurrency I/O (thousands of network connections) where the overhead of thread context-switching becomes prohibitive. The decision tree: CPU-bound → multiprocessing, low-concurrency I/O → threading, high-concurrency I/O → asyncio.
- What is __init__ vs __new__ in Python?
- `__new__` is the constructor. It allocates the object and returns the new instance. `__init__` is the initializer; it sets up the instance after `__new__` has created it. For ordinary classes you only override `__init__`; `__new__` is rarely needed unless you're subclassing an immutable type (like `int`, `str`, or `tuple`), implementing a singleton pattern, or building a metaclass. The exam-worthy distinction is that `__new__` is a static method (it receives the class as its first argument) while `__init__` is an instance method (it receives the already-created instance).
- What are dunder methods in Python?
- Dunder (double-underscore) methods are special methods Python invokes implicitly for built-in operations. `__init__` runs on instance creation; `__str__` and `__repr__` are called by `print` and the REPL; `__len__` enables `len(obj)`; `__getitem__` enables `obj[key]`; `__iter__` and `__next__` enable iteration; `__eq__` and `__hash__` enable equality and use as a dict key; `__enter__` and `__exit__` enable use as a context manager. Implementing dunder methods is how you make your own classes behave like built-in types. It's the principle Python's documentation calls 'duck typing.' The interview question is often: name three dunder methods you've implemented in a real project and what they did.
- What is the difference between a shallow copy and a deep copy?
- A shallow copy creates a new container but the inner objects are the same references. Modifying a nested list inside a shallow copy modifies the original. A deep copy recursively copies every nested object, producing a fully independent tree. The `copy` module provides both: `copy.copy()` for shallow, `copy.deepcopy()` for deep. The interview-relevant case is mutable defaults. `def f(x=[])` is a classic Python gotcha because the default list is created once at function-definition time and shared across calls. Using `None` and creating the list inside the function is the canonical fix.
- How do you handle exceptions in Python?
- Use `try/except/else/finally`. `try` wraps the code that might raise; `except` catches specific exception types (always specific, never bare `except:`); `else` runs only if no exception was raised; `finally` always runs, used for cleanup. Custom exceptions inherit from `Exception` (not `BaseException`, which is for system-level interrupts). The 2026 best practice is to chain exceptions with `raise NewException(...) from original_exception` so the traceback preserves the cause. Context managers (`with` blocks) are the cleaner alternative when the cleanup is resource-oriented.
- What are Python context managers and the with statement?
- A context manager is an object that defines `__enter__` and `__exit__` methods to set up and tear down a resource. The `with` statement guarantees `__exit__` runs even if an exception is raised inside the block. That makes it the canonical pattern for files, locks, database connections, and any resource that must be released. The `contextlib` module provides `@contextmanager` to write context managers as generator functions (yield once between setup and teardown) instead of writing a full class. Use a context manager whenever the resource has a clear lifecycle; it's almost always cleaner than try/finally.
- What is duck typing in Python?
- Duck typing is the principle that an object's suitability for an operation is determined by whether it has the required methods, not by its inherited type. 'If it walks like a duck and quacks like a duck, it's a duck.' A function that calls `obj.read()` will work on any object with a `read` method, regardless of its class. Python prefers duck typing over the explicit type-checking of statically-typed languages. The 2026 nuance is that type hints (PEP 484, expanded by Protocols in PEP 544) give you the option of static-type-checking your duck types without giving up the runtime flexibility.
- How should I prepare for a Python interview as a CS new grad?
- Three weeks of focused work. Week 1: drill the language-specific concepts your coursework probably skipped. Decorators, generators, the GIL, context managers, dunder methods. Week 2: solve 40-50 LeetCode-style problems using Python idiomatically (`enumerate`, comprehensions, `collections.Counter`, `defaultdict`, `heapq`) rather than translating Java or C++ patterns. Week 3: run timed mock interviews on the canonical questions from this guide, narrating your reasoning out loud. The interview question depth is usually shallow for new grads but the language-specific surface area is wide. Knowing 20 concepts at moderate depth beats knowing 5 deeply.
- What's the most common Python interview mistake new grads make?
- Writing Python that looks like Java. Initializing an empty list and appending in a loop when a comprehension would do; using a counter dict when `collections.Counter` does it in one line; iterating with `range(len(arr))` when `enumerate(arr)` is cleaner; reaching for a class when a function would work. Interviewers grade idiom fluency, not just correctness. The candidate who knows Python well writes shorter, more readable code. The difference is visible inside two minutes of a coding round.