100 Real-Time Python Interview Questions and Answers 2026
Practice 100 current Python interview questions with clear answers, code examples, concurrency trade-offs, and practical troubleshooting for 2026.

“Real-time” here means current 2026 interview preparation. It does not mean real-time operating-system deadlines. The 100 questions below cover Python fundamentals, the data model, collections, functions, exceptions, iteration, object-oriented design, typing, packaging, testing, performance, concurrency, and practical coding. The count is an editorial scope, not a ranking of the questions interviewers ask most often.
For version-specific answers, check the Python version used by the role. This guide aligns its concurrency explanations with the Python 3.14.7 documentation.
How to use this guide
- Answer each question aloud before reading the model answer.
- Explain trade-offs and give a small example instead of reciting a definition.
- Run the code snippets locally and change the inputs.
- For concurrency questions, identify whether the workload is I/O-bound or CPU-bound before choosing an API.

Python fundamentals: questions 1–15
- What is Python?
Python is a high-level, general-purpose language with dynamic typing, automatic memory management, and a large standard library. Its syntax emphasizes readability. - Is Python compiled or interpreted?
Source is compiled to bytecode, then executed by a Python virtual machine. The implementation details vary, so “interpreted” alone is incomplete. - What does dynamic typing mean?
Names do not have fixed declared types; objects do. A name can refer to objects of different types during execution. - What is duck typing?
Code depends on an object’s supported behavior rather than its declared class: if it provides the needed methods, it can be used. - What is PEP 8?
It is the main style guide for Python code. It covers naming, indentation, imports, whitespace, and line length. - Why is indentation significant?
Indentation defines suites and nesting. Inconsistent indentation causes a syntax error instead of merely changing formatting. - What is a Python statement?
A statement performs an action, such as assignment, import, return, or a loop. Expressions produce values and can appear inside statements. - What is the difference between
==andis?==compares values through equality methods;ischecks object identity. Useis Nonefor the singletonNone. - What are truthy and falsy values?
False,None, numeric zero, and empty containers are falsy by default. Most other objects are truthy unless they define otherwise. - What is
None?Noneis the singleton representing the absence of a value. Functions without an explicit return usually return it. - What is a comment?
A comment begins with#and is ignored by the interpreter. Use comments to explain intent, not obvious syntax. - What is a docstring?
A string literal placed first in a module, class, or function becomes documentation available through__doc__and documentation tools. - What is variable scope?
Python resolves names using the LEGB order: local, enclosing, global, and built-in scopes. - What do
globalandnonlocaldo?globalrebinds a module-level name from a function;nonlocalrebinds a name in an enclosing function scope. - What is a virtual environment?
It is an isolated environment with its own interpreter and installed packages, preventing project dependencies from colliding.
Data model, mutability, and memory: questions 16–30
- What is an object?
Every value is an object with identity, type, and value. Types define supported operations. - Mutable versus immutable?
Mutable objects can change in place, such as lists and dictionaries. Immutable objects, such as strings and tuples, require a new object for a different value. - Why can a tuple contain a mutable list?
The tuple’s references cannot change, but a referenced list can mutate. Immutability is not recursively applied to contained objects. - What is object identity?
Identity distinguishes a particular object during its lifetime.id()exposes an implementation-oriented identity value. - How does assignment work?
Assignment binds a name to an object; it does not copy the object. - What is aliasing?
Two or more names alias when they reference the same object. Mutating through one name is visible through the others. - Shallow copy versus deep copy?
A shallow copy duplicates the outer container and keeps references inside. A deep copy recursively copies reachable objects when possible. - How does garbage collection work?
CPython primarily uses reference counting and also detects reference cycles with a cyclic garbage collector. Do not rely on collection timing for resource cleanup. - What is reference counting?
Each object tracks references. When the count reaches zero in CPython, its memory can usually be reclaimed immediately. - What is interning?
Implementations may reuse identical immutable objects, often small integers or strings. Never use identity comparisons as a value-comparison shortcut. - What are weak references?
They refer to an object without keeping it alive, useful for caches and observer registries. - What is hashability?
An object is hashable when it has a stable hash and equality behavior, allowing use as a dictionary key or set member. - Why are lists unhashable?
Lists are mutable, so their contents and therefore a derived hash could change while stored in a hash table. - What is the descriptor protocol?
Objects defining methods such as__get__,__set__, or__delete__control attribute access. Properties and methods use descriptors. - What is
__slots__?
It declares allowed instance attributes and can remove the per-instance dictionary. It changes inheritance and weak-reference behavior, so measure before using it.
Collections and complexity: questions 31–45
- List versus tuple?
Use lists for mutable sequences and tuples for fixed records or values that should be hashable when their contents are hashable. - List versus set?
Lists preserve order and allow duplicates. Sets provide uniqueness and average constant-time membership checks. - Dictionary lookup complexity?
Average lookup, insertion, and deletion are O(1), with hash collisions and resizing affecting constants. - What does dictionary order mean?
Modern Python preserves insertion order as part of the language specification. Do not confuse order preservation with sorted order. - What is
defaultdict?
It creates a default value through a factory when a missing key is accessed, simplifying grouping and counting. - What is
Counter?
It is a dictionary subclass for counting hashable values and supports operations such as most-common queries. - What is a deque?
collections.dequesupports efficient appends and pops at both ends, making it suitable for queues. - What is slicing?
A slice selects a range using start, stop, and step. It normally creates a new sequence rather than a view. - What is a list comprehension?
It creates a list from an iterable with optional filtering in one expression. Avoid nesting that harms readability. - What is a generator expression?
It computes values lazily and usually uses less memory than constructing a complete list. - How do you sort custom objects?
Passkey=tosorted()orlist.sort(). Usefunctools.cmp_to_keyonly when a comparison function is unavoidable. sort()versussorted()?list.sort()mutates a list and returnsNone.sorted()returns a new sorted iterable result.- What is stable sorting?
Equal-key elements retain their original relative order. This enables multi-pass sorting by secondary and primary keys. - How do sets compare?
Union combines members, intersection keeps shared members, difference removes members, and symmetric difference keeps members in exactly one set. - How do you choose a collection?
State access patterns first: indexed access, membership, uniqueness, insertion order, queue operations, or key lookup.
Functions, closures, and decorators: questions 46–58
- What is a first-class function?
Functions can be stored, passed as arguments, returned, and attached to data structures. - Positional versus keyword arguments?
Positional arguments match by order; keyword arguments match parameter names. Keyword-only parameters make APIs clearer. - What are
*argsand**kwargs?
They collect extra positional and keyword arguments. Their names are conventional; the stars perform unpacking and collection. - What is a default-argument trap?
Defaults are evaluated once when the function is defined. Avoid mutable defaults; useNoneand create a value inside. - What is a closure?
A nested function remembers names from its enclosing scope after that scope returns. - What is late binding?
Closures look up free variables when called. Capture a loop value with a default argument or a factory when needed. - What is a lambda?
A lambda is a small anonymous expression function. Usedeffor multi-step logic or documentation. - What is a decorator?
It receives a callable and returns a wrapped or replacement callable. Preserve metadata withfunctools.wraps. - What is recursion?
A function calls itself with a base case and a smaller subproblem. Python recursion has a depth limit, so iteration may be safer. - What is a pure function?
It depends only on arguments and has no observable side effects, making it easier to test and cache. - What is memoization?
It caches results for repeated inputs.functools.lru_cacherequires hashable arguments and bounded cache policy. - What are annotations?
They attach metadata to parameters and returns. Python does not automatically enforce them at runtime. - What is
functools.partial?
It creates a callable with some arguments pre-filled, useful for adapting APIs.
Exceptions and resource management: questions 59–68
- What is an exception?
It is an object describing an abnormal condition that interrupts normal control flow. - How do
try,except,else, andfinallydiffer?excepthandles selected errors,elseruns when none occurred, andfinallyruns during cleanup. - Why catch specific exceptions?
Specific handlers preserve unexpected failures and make recovery behavior predictable. - What is exception chaining?
Raising a new exception while handling another records the original cause. Useraise NewError from err. - When should you raise?
Raise when a function cannot honor its contract. Include actionable context and choose an appropriate exception type. - What is a custom exception?
A class inheriting fromExceptionthat represents a domain-specific failure. - What is a context manager?
It defines setup and cleanup around awithblock through__enter__/__exit__orcontextlib. - Why use
with open(...)?
It closes the file even when the block raises an exception. - Should you use bare
except?
Usually no. It also catches interrupts and system-exit exceptions; catchExceptionor narrower types deliberately. - How do you log an exception?
Use the logging module withlogger.exception()inside the handler to include a traceback.
Iterators and generators: questions 69–76
- What is an iterable?
An object that can return an iterator, commonly through__iter__. - What is an iterator?
It supplies__next__and raisesStopIterationwhen exhausted. - What does
iter()do?
It obtains an iterator from an iterable, or uses the two-argument callable sentinel form. - What does
yielddo?
It pauses a generator function and returns a value; the next call resumes from that point. - Why use generators?
They stream data and avoid storing the entire result, which helps with large inputs. - What is
yield from?
It delegates iteration to another iterable and forwards values and generator completion details. - Can a generator be restarted?
No. Once exhausted, create a new generator object. - How do you close a generator?
Callclose(), which raisesGeneratorExitinside it and allows cleanup.
Object-oriented Python: questions 77–86
- Class versus instance?
A class defines behavior and shared attributes; an instance stores per-object state. - What is inheritance?
A class reuses or overrides behavior from base classes. Prefer composition when the relationship is not truly “is-a.” - What is method resolution order?
MRO defines the order Python searches classes for attributes and methods, using C3 linearization. - What does
super()do?
It follows the MRO to call the next implementation, supporting cooperative multiple inheritance. - What is encapsulation in Python?
It is a convention supported by naming, properties, and carefully designed interfaces rather than enforced private fields. - What is polymorphism?
Different objects respond to the same operation according to their own implementation. - What is an abstract base class?
It defines an interface and can require subclasses to implement abstract methods. - What is a dataclass?
dataclasses.dataclassgenerates methods such as__init__and__repr__from declared fields. - What is operator overloading?
Dunder methods such as__add__define how operators work for a type. - What is composition?
An object contains collaborators and delegates work to them, reducing inheritance coupling.
Typing, modules, and packaging: questions 87–93
- What is a type hint?
It documents expected types for humans and static tools. Runtime enforcement requires separate tooling or code. - What is
Optional?
It indicates a value may be a type orNone; modern syntax is oftenstr | None. - What is a protocol?
A structural interface describing required attributes and methods, allowing compatible types without inheritance. - Module versus package?
A module is usually one Python file. A package organizes modules under a common import namespace. - Why use
if __name__ == '__main__'?
It runs CLI code only when the file is executed directly, not when imported. - What is an import cycle?
Two modules depend on each other during initialization. Move shared code, import locally, or redesign boundaries. - What belongs in project packaging metadata?
Project name, version, dependencies, supported Python versions, entry points, and build configuration.

Testing, debugging, and performance: questions 94–98
- Unit versus integration test?
A unit test isolates a small component. An integration test checks collaboration with real or realistic dependencies. - What is mocking?
Replacing a dependency with a controllable test double. Mock boundaries, not every internal implementation detail. - How do you debug a failure?
Reproduce it, reduce the input, inspect the traceback, add targeted logging or a debugger breakpoint, then add a regression test. - How do you optimize Python?
Measure first with a profiler, improve the algorithm or I/O pattern, then benchmark representative workloads. Avoid optimizing based on intuition alone. - What is Big-O complexity?
It describes how resource use grows with input size. State time and space complexity and the assumptions behind them.
Concurrency and practical coding: questions 99–100
- When would you use asyncio, threads, or processes?
asynciouses cooperativeasync/awaittasks and often fits high-level I/O-bound network code. Threads overlap blocking I/O and share memory, but conventional CPython limits one thread to executing Python bytecode at a time because of the GIL. Processes provide separate interpreters and are the documented choice when CPU-heavy Python bytecode must use multiple cores. The threading documentation describes these trade-offs, while the asyncio documentation covers asynchronous concurrency. A GIL does not make shared-state code automatically race-free; use locks and clear ownership. Free-threaded builds can disable the GIL beginning with Python 3.13, but they are not the default configuration. - How would you solve a practical coding problem in an interview?
Clarify inputs and outputs, state assumptions, propose a simple approach, discuss complexity, implement readable code, test edge cases, and explain how you would improve it. For example, to find duplicate values:def duplicates(values): seen = set() result = set() for value in values: if value in seen: result.add(value) else: seen.add(value) return resultThis runs in average O(n) time and O(n) space.
Runnable concurrency examples
Asyncio for network-style waits
import asyncio
async def work(name, delay):
await asyncio.sleep(delay)
return f'{name} done'
async def main():
results = await asyncio.gather(work('a', 1), work('b', 1))
print(results)
asyncio.run(main())
The sleeps overlap because each coroutine yields control. Replacing them with a blocking synchronous call would block the event loop unless that work is moved to an executor or an asynchronous library is used.
Threads for blocking I/O
from concurrent.futures import ThreadPoolExecutor
def fetch(name):
# Replace with a blocking network or file operation.
return f'{name} complete'
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(fetch, ['a', 'b', 'c'])))
Processes for CPU-heavy work
from concurrent.futures import ProcessPoolExecutor
def square(value):
return value * value
if __name__ == '__main__':
with ProcessPoolExecutor() as pool:
print(list(pool.map(square, range(10))))
Common interview mistakes and fixes
| Mistake | Fix |
|---|---|
| “The GIL makes threads useless.” | Explain that threads can overlap I/O; the limitation concerns parallel Python bytecode in conventional CPython. |
| “Async makes every call non-blocking.” | Verify that the libraries used expose asynchronous operations. |
Using is for strings or numbers. |
Use equality for values and identity only for singletons such as None. |
| Mutable default arguments. | Use a None sentinel and allocate inside the function. |
| Catching every exception. | Catch the narrowest expected type and preserve unexpected tracebacks. |
| Optimizing before measuring. | Profile representative data and report the complexity change. |
| Ignoring cleanup. | Use context managers for files, locks, and other resources. |
Or skip the browser setup
If an interview exercise or internal tool needs screenshots of documentation, dashboards, or rendered pages, ScreenshotNeo provides a single GET request that returns PNG, JPEG, WebP, or PDF. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.
See the ScreenshotNeo API documentation for all options.
cURL
curl -G 'https://api.screenshotneo.com/v1/shot' -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
open('shot.webp', 'wb').write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
You can also choose full-page capture with lazy images loaded, a CSS-selected element, dark mode, device presets or custom viewports, retina scale, PDF paper and margin settings, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture, and usage reporting. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free. Create a free ScreenshotNeo account.
Short FAQ
Are these guaranteed interview questions?
No. The 100-question count is an editorial study set, not a verified frequency ranking.
Which Python version should I prepare for?
Ask the employer. Use the role’s stated version and verify version-specific behavior in its official documentation.
Should I memorize APIs?
Memorize core concepts and practice finding exact API details quickly. Interviewers usually learn more from your reasoning and trade-offs.
Is asyncio always faster?
No. It can improve throughput for suitable I/O workloads, but blocking calls, CPU-heavy work, and poor coordination can remove the benefit.
Does a free-threaded build remove all synchronization needs?
No. Shared mutable state still requires deliberate synchronization and thread-safety design.


