Search for AI Courses, Tech News and, Blogs

Python Interview Questions: The Tested Question Set Companies Actually Ask

by Jon Weatherhead | 1 week ago | 15 min read

Anyone who has watched candidates prepare knows the pattern. They memorise the difference between a list and a tuple, then freeze the moment an interviewer asks why that difference matters for a hash key. The questions that decide offers are rarely trivia. They test whether a person understands how Python behaves under the hood and can reason about trade-offs while typing.

The set below is grouped by difficulty so preparation can move from warm-up to pressure. Companies known for asking versions of these include the ones listed here, drawn from published interview experiences and engineering blogs rather than guesswork.

How to use this set: Read the question, cover the answer, and speak the response before checking. Interviewers score clarity of reasoning, not word-perfect recall. If a follow-up column is shown, expect it, because that is where most candidates lose points.

1. Core language and data types Warm-up

These open almost every phone screen. The goal is not to catch anyone out. It is to confirm the basics are genuinely solid before the round moves on. Answering with a concrete reason, not just a definition, is what separates a pass from a strong pass.

Questions to ask in your next tech interview | Gravitas

Q1 What is the difference between a list and a tuple, and when does it matter?

Easy

A list is mutable and a tuple is immutable. The practical point interviewers want: because tuples are immutable and hashable, they can be dictionary keys or set members, while lists cannot. Tuples also carry a small memory and speed advantage for fixed collections.

Q2 How does is differ from ==?

Easy

== compares values, is compares identity, meaning whether two names point to the same object in memory. A frequent trap: small integers and short strings are cached by CPython, so a is b can return True for 256 but False for 257. The rule to state is that is should be reserved for None checks.

Q3Explain mutable versus immutable with a bug it causes.

Easy

Strings, numbers, and tuples are immutable; lists, dicts, and sets are mutable. The classic bug is a mutable default argument:

def add(item, bucket=[]):   # bucket is created once    bucket.append(item)    return bucket add(1)   # [1]add(2)   # [1, 2]  not [2]

The fix is bucket=None then assign inside the function.

Q4 What does a list comprehension give over a loop, and where is a generator better?

Easy+

A comprehension is faster and reads as one expression. A generator expression, written with parentheses, produces items lazily and holds one at a time, so it wins on memory for large or infinite streams. Saying "use a generator when the full list will not fit comfortably in memory" lands well.

StructureOrderedMutableDuplicatesTypical use
listYesYesYesOrdered, changing sequence
tupleYesNoYesFixed record, dict key
setNoYesNoMembership, dedup
dictYes (3.7+)YesKeys uniqueLookups by key

Memory, the GIL, and internals Screening

This section decides whether a candidate is treated as junior or mid-level. Companies with heavy backend and infrastructure work, Uber and Nvidia among them, lean on it hard because performance problems trace back here.

Top Tips To Ace An Interview

Q5 What is the Global Interpreter Lock, and how does it shape design?

Medium

The GIL is a mutex in CPython that lets only one thread execute Python bytecode at a time. Threads still help with input and output bound work because the lock releases during blocking calls, but they do not speed up CPU bound work. For parallel computation the answer is multiprocessing or a native extension. Worth adding: the free-threaded build introduced in 3.13 is moving toward removing this constraint.

Q6 How does Python manage memory and garbage collection?

Medium

CPython uses reference counting as the primary mechanism, freeing an object the moment its count hits zero. A cyclic garbage collector runs on top to catch reference cycles that counting alone cannot reclaim. Mentioning that objects live in a private heap managed by the interpreter shows depth.

Q7 Deep copy versus shallow copy: what actually differs?

Medium

A shallow copy duplicates the outer container but shares references to nested objects, so mutating a nested list shows up in both copies. A deep copy recursively duplicates everything. Naming copy.copy and copy.deepcopy and the performance cost of the deep version is the complete answer.

Threading

Best for I/O bound tasks: network calls, file reads, waiting on a database. The GIL releases during the wait.

Multiprocessing

Best for CPU bound tasks: each process has its own interpreter and memory, sidestepping the GIL at the cost of heavier startup.

Object-oriented Python Onsite

Design-leaning roles push here. Microsoft and Atlassian interviewers often start with a small class and grow it, watching how the candidate reasons about inheritance and encapsulation.

Q8 What is the difference between __init__ and __new__?

Medium+

__new__ creates and returns the instance; __init__ initialises the already-created instance. Overriding __new__ is rare and shows up when subclassing immutable types or building singletons. Most day-to-day code only touches __init__.

Q9 Explain method resolution order and how Python handles multiple inheritance.

Hard

Python uses the C3 linearisation algorithm to build a single, predictable ordering of parent classes. ClassName.__mro__ or .mro() reveals it. The diamond problem is resolved by this order, and super() follows the MRO rather than calling a parent directly, which is why cooperative super() calls matter in mixins.

Q10 Class variable versus instance variable, with a gotcha.

Medium

A class variable is shared across instances; an instance variable belongs to one object. The gotcha is a mutable class variable such as a shared list, where appending through one instance is visible to all. Reassigning through an instance quietly creates a new instance variable instead.

Q11 What do @staticmethod and @classmethod do?

Medium

A class method receives the class as its first argument (cls) and is commonly used for alternative constructors. A static method receives neither instance nor class and is a plain function grouped inside the class for organisation. Giving the from_string factory example for a class method scores well.

4. Decorators, generators, and async Senior signal

Strong answers here move a candidate up a level. Stripe and Netflix are known for probing async and generator internals because their systems live or die on I/O throughput.

Q12 Write a decorator that times a function.

Medium

import functools, time def timed(fn):    @functools.wraps(fn)    def wrapper(*args, **kwargs):        start = time.perf_counter()        result = fn(*args, **kwargs)        print(f"{fn.__name__}: {time.perf_counter()-start:.4f}s")        return result    return wrapper

The detail interviewers wait for is functools.wraps, which preserves the wrapped function's name and docstring. Forgetting it is a common ding.

Q13 What is the difference between an iterator and a generator?

Medium

An iterator is any object implementing __iter__ and __next__. A generator is a simpler way to build one using yield, which suspends and resumes state automatically. Generators are lazy and memory-light, which is the reason to reach for them on large data.

Q14 What does yield do, and how does a generator hold state?

Medium+

yield pauses the function, returns a value, and freezes local state until the next call resumes right after the yield. Because state lives in the frame, the whole sequence never needs to exist in memory at once.

Q15 Explain async and await in plain terms.

Hard

Asyncio runs a single-threaded event loop. await hands control back to the loop while a coroutine waits on I/O, letting other coroutines run in the gap. It is concurrency without threads, ideal for thousands of network calls, and it does not help with CPU bound work because nothing yields during pure computation.

Q16What is a context manager and why use with?

Medium

A context manager defines __enter__ and __exit__ so setup and cleanup happen automatically, even if an exception fires. The everyday case is file handling, where with open(...) guarantees the file closes. The contextlib.contextmanager decorator builds one from a generator.

Live coding problems The real test

Every list of Python questions repeats FizzBuzz. Real loops move past it fast. Below are the problems that recur in shared write-ups, with the pattern each one is really checking.

ProblemPattern testedOptimal complexitySeen at
Two SumHash map lookupO(n) time, O(n) spaceAmazon, Google
Reverse a linked listPointer manipulationO(n) time, O(1) spaceMeta, Microsoft
Valid anagramCounting with dictO(n) timeAdobe, Airbnb
Merge intervalsSorting then sweepO(n log n)Google, Stripe
LRU cacheDict + doubly linked listO(1) get/putAmazon, Atlassian
Longest substring, no repeatSliding windowO(n) timeMeta, Spotify

Q17 Solve Two Sum and explain the trade-off.

Medium

def two_sum(nums, target):    seen = {}    for i, n in enumerate(nums):        need = target - n        if need in seen:            return [seen[need], i]        seen[n] = i    return []

The brute force is O(n squared). The hash map version trades O(n) extra space for O(n) time. Stating that trade-off out loud is often worth more than the code itself.

Q18 Find the first non-repeating character in a string.

Medium

from collections import Counter def first_unique(s):    counts = Counter(s)    for i, ch in enumerate(s):        if counts[ch] == 1:            return i    return -1

Reaching for collections.Counter signals fluency with the standard library, a detail Salesforce and Uber reviewers note.

Q19 Reverse a singly linked list in place.

Hard

def reverse(head):    prev = None    while head:        nxt = head.next        head.next = prev        prev = head        head = nxt    return prev

The three-pointer walk is the expected O(1) space solution. Doing it recursively is fine too, but the interviewer will ask about stack depth.

A pattern worth memorising: the sliding window covers a surprising share of string and array questions asked at Meta and Spotify. Two Sum trains the hash-map habit, and merge intervals trains sort-then-sweep. Drilling those three patterns prepares a candidate for far more than three questions.

Quick-fire warm-ups still asked

  • FizzBuzz as a nerves check, usually with a twist such as replacing print with a list return.
  • Palindrome check using slicing s == s[::-1], then asked to do it without extra space.
  • Count word frequency in a paragraph, steering toward Counter or defaultdict.
  • Flatten a nested list, which opens a discussion of recursion versus a stack.
  • Fibonacci, then a follow-up on memoisation with functools.lru_cache.

Machine-coding and system questions Final rounds

Senior loops replace puzzles with open builds. The prompt is broad, and the score comes from structure, naming, and how the candidate handles edge cases without being told.

Design a rate limiter

Token bucket or sliding window. Watch for thread safety and what happens at the reset boundary.

Build an in-memory key-value store

Support get, set, and TTL expiry. Extension: add a snapshot or transaction.

Parse and query a log file

Stream with a generator instead of loading it whole. Aggregate by field.

URL shortener

Encoding scheme, collision handling, and the lookup data structure.

Q20 How would exceptions be handled in a service that must never crash on one bad record?

Medium

Catch the narrowest exception type around the risky operation, log the offending record with context, continue the loop, and surface a count of failures at the end. The anti-pattern to call out is a bare except: that swallows everything including KeyboardInterrupt.

The rest of the set, in brief

#QuestionOne-line anchor
22Difference between append and extendAdd one item vs merge an iterable
23How does dict maintain insertion order?Guaranteed since 3.7, was an implementation detail in 3.6
24What is a lambda and its limit?Single expression, no statements
25Explain __slots__Skips per-instance dict, saves memory
26Difference between @property and a methodAttribute access syntax with logic behind it
27What does zip return in Python 3?A lazy iterator, not a list
28How does string interning work?CPython caches some strings for identity speed
29Explain try / except / else / finallyelse runs only if no exception
30What is duck typing?Behaviour over declared type
31Difference between sort and sortedIn place vs returns a new list
32What is a metaclass?The class of a class, controls creation
33How to merge two dicts in modern Python?The | operator since 3.9
34Explain enumerate and its start argumentIndex and value without manual counters
35What is monkey patching?Replacing attributes at runtime, use sparingly
36Difference between @abstractmethod and a normal methodForces subclasses to implement
37How does defaultdict differ from dict?Auto-creates missing keys with a factory
38What is the walrus operator?Assignment inside an expression, :=
39Explain truthiness of empty containersEmpty list, dict, string are falsy
40Difference between range and a listrange computes on demand
41How do type hints affect runtime?They do not, unless a tool enforces them
42What is __repr__ vs __str__?Debug view vs readable view
43Concurrency versus parallelismInterleaving vs simultaneous execution
44How to profile slow Python code?cProfile, then targeted timeit
45Why do dict keys need hash and equality?Keys need consistent hash and ==

Common ways candidates lose the room

Reviewing feedback forms surfaces the same failures again and again. Knowing the answer is only half the battle; how it is delivered decides the rest.

  • Jumping to code before clarifying. Strong candidates restate the problem and ask about input size and edge cases first. It costs thirty seconds and changes the whole score.
  • Silence while thinking. Interviewers cannot grade a blank screen. Narrating the approach, even a rough one, keeps the signal flowing.
  • Ignoring complexity. A working solution with no mention of time or space reads as incomplete at mid-level and above.
  • Over-engineering the warm-up. Reaching for a metaclass on FizzBuzz reads as showing off, not skill.
  • Not testing the output. Walking through one example by hand at the end catches off-by-one errors before the interviewer does.

Preparation plan that works: spend the first week on sections one to three until every answer is automatic, the second week drilling the six coding patterns above, and the final days rehearsing out loud with a timer. Speaking answers is a different skill from knowing them, and it is the one that gets tested.

Final verdict

After working through these questions in mock rounds and comparing them against what candidates actually report from real loops, one thing stands out. The interview is not a memory test. Every question here rewards a person who can explain the reasoning behind a choice, name the trade-off, and stay calm through a follow-up. A candidate who understands why a tuple can be a dict key, why the GIL shapes a threading decision, and why a generator saves memory will handle variants of these questions that no list can fully predict.

The forty-five questions in this set are not exhaustive, and no set could be. What they do is cover the ground that keeps recurring at the companies named at the top, from the warm-up screen to the senior machine-coding round. Time spent here is time spent on the parts of Python that interviewers genuinely care about, rather than trivia that rarely decides an offer. Prepare the patterns, practise speaking the answers, and the questions on the day will feel familiar rather than foreign.