Here, “real-time” means current interview preparation—not software with hard real-time deadlines. This is an editorial set of 100 questions, not a ranking of the questions interviewers ask most often. Version-specific notes refer to the Python 3.14.7 documentation, updated September 28, 2026 (Python 3.14 documentation).
Use the answers as concise starting points: explain the concept, name a relevant tradeoff, and connect it to the workload or code in the question. For concurrency, in particular, choosing among asyncio, threads and processes depends on the kind of work—not just personal preference.
Python fundamentals
- What is Python?
Python is a high-level, general-purpose programming language. Its emphasis on readable syntax supports a wide range of uses, from scripting to web services and data processing. - Is Python compiled or interpreted?
Both labels can be misleading on their own. CPython typically compiles source to bytecode and executes it on a virtual machine; other implementations can differ. - What is dynamic typing?
Types belong to objects, and a variable name can refer to objects of different types over time. Dynamic typing does not mean values lack types. - What is strong typing?
Python generally does not silently treat unrelated types as interchangeable. For example, adding a string and an integer raises aTypeErrorunless the program converts or otherwise handles them. - What is the difference between
==andis?==tests value equality;istests object identity. Useis Nonefor the conventional null check, not identity comparisons for ordinary value equality. - What does
Nonemean?Noneis the singleton object commonly used to represent an absent value or a function result with no meaningful return value. It is distinct fromFalse, zero and an empty collection. - What are truthy and falsy values?
Values such asNone,False, numeric zero and empty collections are false in a Boolean context; most other objects are true. Custom classes can define truth testing with__bool__or__len__. - What is a namespace?
A namespace maps names to objects. Modules, functions and classes introduce namespaces; Python’s scope rules determine which namespace a name lookup searches. - What is PEP 8?
PEP 8 is Python’s style guide. It recommends conventions for readable, consistent code; teams may adopt additional rules for their projects. - What is the Zen of Python?
It is a set of aphorisms about Python design, accessible by runningimport this. It expresses guiding preferences, not strict language rules.
Objects, mutability and collections
- What is the difference between mutable and immutable objects?
A mutable object can be changed after creation; an immutable object cannot. Lists and dictionaries are mutable; integers and strings are immutable. A name can be rebound regardless of the mutability of the object it previously referred to. - What is the difference between a list and a tuple?
Both are ordered sequences. Lists are mutable; tuples are immutable containers. A tuple can contain a mutable object, so immutability of the tuple does not make every object reachable through it immutable. - What is a dictionary?
A dictionary maps hashable keys to values. It is useful for lookup by key; keys must remain hash-stable while stored. - What is a set?
A set holds distinct hashable elements and supports membership tests and set operations such as union and intersection. It is not a sequence for positional indexing. - What does hashable mean?
An object is hashable when it has a hash value that remains stable during its lifetime and can be compared for equality. Hashability enables use as a dictionary key or set member. - Why can’t a list be a dictionary key?
A list is mutable and unhashable. If a key’s hash changed after insertion, dictionary lookup could no longer reliably find it. - What is slicing?
Slicing selects a range from a sequence withsequence[start:stop:step]. The start is included and stop excluded; omitted values use defaults. A slice produces a new sequence for built-in lists and strings. - What is a shallow copy?
A shallow copy creates a new outer container but reuses references to its contained objects. Changes to a nested mutable object can therefore be visible through both containers. - How is a deep copy different?
A deep copy recursively copies objects where possible, usingcopy.deepcopy. It is not always appropriate: copying may be costly or unsuitable for objects tied to external resources. - What is the complexity of dictionary lookup?
Dictionary lookup is typically expected O(1), but behavior depends on hashing and collisions; pathological cases can take longer. State assumptions rather than treating average-case complexity as a guarantee. - When would you use a deque rather than a list?
Usecollections.dequefor efficient appends and pops at either end, such as a queue. A list is more suitable for fast indexed access and appending at the end. - What is a list comprehension?
It is a compact way to build a list from an iterable, optionally filtering items, as in[x * 2 for x in values if x > 0]. Use a loop when it makes complex logic easier to read. - What is the difference between
sort()andsorted()?list.sort()sorts a list in place and returnsNone.sorted(iterable)returns a new sorted list and accepts any iterable. - What is unpacking?
Unpacking assigns elements from an iterable to names, such asa, b = pair. Extended unpacking uses a starred name, such asfirst, *middle, last = values. - What is an f-string?
An f-string embeds expressions in a string:f"Hello, {name}". It is useful for readable formatting; untrusted input should not be evaluated as code merely to format it.
Functions, scope and closures
- What is the difference between a parameter and an argument?
A parameter is a name in a function definition; an argument is the value supplied when calling the function. - What are positional and keyword arguments?
Positional arguments are matched by position; keyword arguments are matched by parameter name. Keyword arguments can make calls clearer where values might otherwise be ambiguous. - Why are mutable default arguments risky?
Default expressions are evaluated once when the function is defined, not once per call. A list or dictionary default can retain changes across calls. Prefer a sentinel such asNone, then create a fresh value inside the function. - What do
*argsand**kwargsdo?*argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dictionary. They are also used to unpack values when calling a function. - What is a lambda?
A lambda is a small anonymous function containing one expression. Usedefwhen the logic needs multiple steps, a descriptive name or a docstring. - What is a closure?
A closure is a function that retains access to names from its enclosing lexical scope after that outer function has returned. - What is the LEGB rule?
Name lookup searches Local, Enclosing, Global and Built-in scopes, in that order.nonlocalandglobaldeclarations affect assignment rules, not the basic meaning of those scopes. - What is a decorator?
A decorator takes a function or class and returns a replacement, commonly to add behavior such as logging or authorization. The@decoratorsyntax applies it at definition time. - Why use
functools.wrapsin a decorator?
It copies useful metadata from the wrapped function, such as its name and docstring, so introspection and documentation remain more informative. - What is a higher-order function?
It accepts a function as an argument, returns a function, or both. Functions are first-class objects in Python, so they can be passed and stored like other values.
Exceptions, files and context managers
- How does exception handling work?
Usetryfor code that may raise, specificexceptclauses for recovery,elsefor success-only work, andfinallyfor cleanup that must run. - Why should you avoid a bare
except?
It can catch exceptions the program should not swallow, including interruption and termination signals represented as exceptions. Catch the narrow exception types the code can handle. - What is the difference between
raiseandraise e?
Inside an exception handler, bareraisere-raises the active exception while preserving its traceback. Raising the caught exception object explicitly can alter traceback presentation. - How do you define a custom exception?
Subclass an appropriate built-in exception, oftenException, and raise it when a domain-specific failure needs to be distinguished by callers. - What does
withdo?
It uses a context manager to set up and reliably clean up a resource. For example,with open(path) as f:closes the file when the block exits, including when an exception occurs. - What are
__enter__and__exit__?
They are the core methods of a synchronous context manager. The first acquires or prepares a resource; the second handles exit and cleanup and can indicate whether an exception should be suppressed. - How should a text file be opened safely?
Usewith open(path, encoding="utf-8") as f:when UTF-8 is the intended encoding. Specify mode and encoding to make behavior explicit across environments. - What is the difference between text and binary file modes?
Text mode reads and writes strings and may perform encoding and newline handling. Binary mode reads and writes bytes without text decoding. - What is exception chaining?
Useraise NewError(...) from originalto preserve the causal link when translating one failure into a higher-level error. - When is
finallyuseful?
It is useful for cleanup that must happen whether a try block succeeds or fails. For managed resources, a context manager is often clearer and less error-prone.
Iterators, generators and comprehensions
- What is an iterable?
An iterable can produce an iterator, usually throughiter(obj). Lists, strings, files and many other objects are iterable. - What is an iterator?
An iterator produces values one at a time through__next__and signals exhaustion withStopIteration. Iterators generally retain their progress. - What does
yielddo?
In a generator function,yieldreturns a value to the caller while suspending the function’s state. The function can resume when the caller requests another value. - How does a generator differ from a list?
A generator yields values on demand rather than storing the entire result as a list. This can reduce memory use for large streams, but a generator is typically consumed once. - What is a generator expression?
It is a lazy expression such as(x * x for x in values). Unlike a list comprehension, it does not build the full result list immediately. - What does
yield fromdo?
It delegates iteration to a sub-iterator or generator, passing its values through and supporting generator delegation semantics. - Why might an iterator raise
StopIteration?
That exception signals that no further items are available. Aforloop handles it internally; callers usingnext()can provide a default value. - How would you process a large file without loading it all into memory?
Iterate over the file object line by line, process each line, and avoid collecting results unless they are needed. For larger pipelines, generators can pass records incrementally.
Object-oriented Python and data model
- What is a class?
A class defines a type’s behavior and can define how its instances store data. An instance is an object created from that class. - What is
self?selfis the conventional name for the instance passed to an instance method. It is explicit in the method definition, although Python supplies it when the method is called on an instance. - What is
__init__?__init__initializes an already-created instance. It is not the method that creates the instance; object creation is associated with__new__. - What is inheritance?
Inheritance lets a class derive behavior from one or more base classes. Use it when the subtype relationship is meaningful; composition can be simpler when an object merely needs another object’s capability. - What is method overriding?
A subclass provides its own implementation of a method defined by a base class. Calls can then dispatch to the implementation appropriate to the object’s type. - What is multiple inheritance?
A class can have multiple base classes. Python uses method resolution order (MRO) to determine lookup order; inspect it withClassName.mro()when behavior is unclear. - What is a class method?
A method decorated with@classmethodreceives the class as its first argument, conventionallycls. It is often used for alternate constructors or class-level behavior. - What is a static method?
A method decorated with@staticmethodreceives no implicit instance or class argument. It groups a utility function under a class when that organization is useful. - What is a property?
A property exposes method-backed behavior through attribute syntax, allowing validation or computed values without changing the public access pattern. - What is a dataclass?
dataclasses.dataclasscan generate common methods such as initialization and representation from annotated fields. It is useful for data-focused classes, but does not automatically validate annotations at runtime.
Typing, modules and packaging
- What are type hints?
Type hints annotate expected types for readers and tools. Python does not generally enforce them at runtime automatically. - What is the difference between
list[int]andList[int]?list[int]is built-in generic syntax supported in current Python versions;typing.Listis the older typing form. Check the project’s minimum Python version and style. - What is
Optional[T]?
It denotes a value that can beTorNone, equivalent in meaning to a union withNone. It does not mean the argument may simply be omitted unless a default allows that. - What is a protocol?
A protocol describes a structural interface: a type can satisfy it by providing the required members, without explicitly inheriting from the protocol. - What is a module?
A module is a Python file or importable unit that provides names such as functions, classes and constants. Importing it makes its names available under a namespace. - What does
if __name__ == "__main__":do?
It runs a block only when the module is executed as the top-level program, not when it is imported as a module. - What is a package?
A package organizes importable modules under a package namespace. Modern Python supports namespace packages, so not every package must have an__init__.pyfile. - What is a virtual environment?
It provides an isolated Python environment for a project’s installed packages, reducing conflicts between project dependencies. Create one withpython -m venv .venv. - What is a dependency file for?
It records project dependencies or constraints so an environment can be recreated more consistently. The right format depends on the project’s packaging and workflow. - Why use
python -m pip?
It runs pip through the selected Python interpreter, helping ensure packages are installed into the environment associated with that interpreter.
Testing, debugging and code quality
- What is a unit test?
A unit test checks a small unit of behavior in isolation as far as practical. Good tests assert outcomes and boundary cases rather than mirroring implementation details. - What is the difference between
unittestand pytest?unittestis in Python’s standard library and uses test classes and assertions. pytest is a separate testing framework with its own conventions and features; choose based on project needs. - What is a mock?
A mock substitutes a dependency so a test can control behavior or verify interactions. Over-mocking can make tests brittle or validate implementation rather than user-visible behavior. - What is a traceback?
A traceback shows the chain of calls leading to an exception, including source locations. Start with the final exception type and message, then inspect the relevant frames. - How do you debug a failing test?
Reproduce it, isolate the smallest failing case, inspect inputs and state at the failure point, and determine whether the defect is in code, assumptions or test setup. Add a regression test after fixing it. - What is logging better for than
print?
Theloggingmodule supports severity levels, configurable handlers and formatting, which makes diagnostic output easier to manage in an application. - What is a linter?
A linter checks code for likely errors or style issues. It complements, rather than replaces, tests and review. - What is code coverage?
Coverage measures which code ran during a test suite, according to a chosen coverage definition. High coverage alone does not establish that tests assert the right behavior.
Performance and practical coding questions
- How do you find a performance bottleneck?
Measure the application under representative inputs, profile it, and optimize the parts shown to dominate runtime. Avoid guessing based only on code appearance. - What is Big O notation?
Big O describes how resource use grows with input size, abstracting away constants and lower-order terms. State what input size represents and whether the claim is average, worst-case or otherwise qualified. - How do you reverse a string?
For a Python string, uses[::-1]. This creates a reversed string; it does not modify the original, because strings are immutable. - How do you remove duplicates while preserving order?
For hashable values in current Python,list(dict.fromkeys(items))preserves insertion order. For unhashable values, choose a comparison strategy appropriate to the data. - How do you count items in a collection?
Usecollections.Counter(items)for a frequency mapping. For a small one-off count, a dictionary loop may be sufficient. - How do you merge two dictionaries?
Use{**a, **b}or, in supported versions,a | b; keys from the right-hand dictionary take precedence. Select syntax compatible with the project’s Python baseline. - How do you safely parse JSON?
Usejson.loads(text)and handlejson.JSONDecodeError. Parsing validates JSON syntax, not your application’s schema or trust requirements. - How would you find the most frequent value?
Count values withCounterand inspectmost_common(1). Consider how ties should be handled if the result must be deterministic by a particular rule. - How do you avoid modifying a list while iterating over it?
Build a new filtered list or iterate over a copy, depending on intent. Mutating the same sequence during traversal can skip or unexpectedly revisit elements. - How would you design a retry?
Retry only failures that may be transient, cap the number or duration of attempts, use a delay strategy, and make repeated operations safe where possible. Do not retry permanent validation errors blindly.
Concurrency: asyncio, threads and processes
These questions are especially sensitive to implementation and workload. The explanations below refer to conventional CPython unless they explicitly say otherwise.
- What is the GIL?
The Global Interpreter Lock in conventional CPython limits execution of Python code to one thread at a time. Python’s threading documentation states: “In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once” (Python 3.14.7 threading documentation). The GIL does not make every operation on application state race-free; synchronization and careful reasoning remain necessary (Python 3.14 C API thread-state and GIL documentation). - When would you use asyncio?
Use it for concurrent I/O-heavy work when the libraries involved offer asynchronous operations. Python’s asyncio documentation describes it as a library for concurrent code withasync/await, often a good fit for I/O-bound and high-level network code (Python 3.14 asyncio documentation). Anasync defdefines a coroutine function; scheduled tasks can make progress as coroutines yield control. A blocking synchronous call still blocks the event loop unless handled appropriately. - How do threads differ from processes for CPU-bound work?
Threads share a process’s memory and can overlap waiting, so they can suit I/O-bound work; in conventional CPython, the GIL limits parallel execution of Python bytecode across threads. Separate processes have distinct memory and add communication and coordination work, but can use more CPU resources for CPU-bound Python bytecode. Python documentsmultiprocessingandProcessPoolExecutoras options for CPU-heavy work (threading documentation). - What is a race condition?
A race condition occurs when a result depends on the timing or interleaving of operations. Shared mutable state can require locks or another coordination design; the GIL is not a substitute for that reasoning. - What is a thread lock?
A lock is a synchronization primitive that allows only one participating thread at a time into a protected critical section. Keep the section small and define a consistent lock order to reduce contention and deadlock risk. - What is a deadlock?
A deadlock is a state where work cannot proceed because participants wait on resources held by one another. Avoid circular lock dependencies, use timeouts where appropriate, and keep resource acquisition order consistent. - What is the difference between concurrency and parallelism?
Concurrency is structuring work so multiple tasks can make progress over overlapping periods; parallelism is executing work at the same instant. An async program can be concurrent without running Python bytecode in parallel across cores. - What does
async/awaitmean?async defdefines a coroutine function, andawaitsuspends that coroutine while an awaitable completes, allowing other event-loop work to proceed. It does not automatically convert blocking code into non-blocking code. - Are free-threaded Python builds the default?
No. Python documentation says free-threaded CPython builds that disable the GIL are available starting with Python 3.13, but are not the default configuration. State the version and build when discussing GIL behavior; compatibility and performance depend on the actual extension stack and workload (Python 3.14.7 threading documentation). - How would you choose a concurrency model for a network scraper?
First check whether the client and surrounding libraries support asynchronous I/O. Asyncio can coordinate many I/O waits; threads can also overlap blocking I/O. If the dominant cost is CPU-heavy parsing in Python, consider processes. Compare complexity, shared-state needs, and measured behavior rather than assuming one model always wins.
Or skip the browser setup
If interview prep includes capturing web pages for examples, test fixtures or documentation, ScreenshotNeo is a website screenshot API and MCP server for developers. It accepts one GET request with a URL and returns a PNG, JPEG, WebP or PDF. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- Cookie banners are accepted and removed before capture; more than 60 known consent platforms, newsletter popups and chat widgets can be removed, with each step switchable.
- Bot checks/CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing; response headers identify the page verdict and whether it was billed.
- An MCP server provides
take_screenshot,get_page_infoandcapture_pdffor Claude, Cursor and other MCP clients. - The free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan.
Sign up for 1,000 free screenshots a month—no card required.
Quick Recap
Best Value
Rank #4
Rank #3
- Book: python interview questions -taming the python: ultimate guide to success: 1
- Binding: paperback
- Language: english
Rank #2
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




