Interview Q&A · Python · 25 questions in this topic
Python Fundamentals — Python Interview Q&A
The vocabulary every Python interview opens with — what the language is, how it executes, how typing and scope work, and the syntax rules that trip up developers arriving from other languages. Part of Python Fundamentals · 375 questions in the Python bank.
What is Python?
Answer
Python is a high-level, general-purpose, interpreted programming language known for readable syntax, dynamic typing, and a large standard library. It supports multiple paradigms — procedural, object-oriented, and functional.
Python was created by Guido van Rossum and first released in 1991. Its design philosophy emphasizes code readability (enforced indentation instead of braces) and a "batteries included" standard library. Python is dynamically typed (types are checked at runtime, not compile time) and automatically memory-managed via reference counting and a cyclic garbage collector.
It runs on the CPython reference implementation (the most common one), but alternative implementations exist — PyPy (JIT-compiled, faster for long-running code), Jython (runs on the JVM), and IronPython (.NET).
Example
# Python reads almost like pseudocode def greet(name): return f"Hello, {name}!" print(greet("Interviewer")) # Hello, Interviewer!
💡 Don't just recite "it's a scripting language." Mention that it's multi-paradigm, interpreted (via bytecode + a virtual machine), dynamically typed, and garbage-collected — that shows you understand why it behaves the way it does in later questions.
What are the key features of Python?
Answer
Python's standout features are readable syntax, dynamic typing, automatic memory management, an extensive standard library, cross-platform portability, and strong support for multiple programming paradigms.
Interviewers usually want a structured list rather than a paragraph. A strong answer groups the features:
Key points
- 1Readability: enforced indentation, minimal boilerplate.
- 2Dynamically typed: no need to declare variable types.
- 3Interpreted: source is compiled to bytecode and run by the Python virtual machine (no separate compile step for the developer).
- 4Automatic memory management: reference counting plus a cyclic garbage collector.
- 5Extensive standard library: file I/O, networking, json, collections, itertools, etc., without external installs.
- 6Multi-paradigm: procedural, object-oriented, and functional styles all work naturally.
- 7Portable: the same source generally runs unmodified on Windows, macOS, and Linux.
- 8Huge ecosystem: PyPI hosts hundreds of thousands of third-party packages.
Example
# Multi-paradigm in one snippet: functional + OOP numbers = [1, 2, 3, 4, 5] squares = list(map(lambda n: n ** 2, numbers)) # functional style class Counter: # OOP style def __init__(self): self.count = 0 def increment(self): self.count += 1
💡 Tailor this answer to the role. For a backend/data role, emphasize the ecosystem (NumPy, Django, FastAPI). For a scripting/automation role, emphasize readability and the standard library.
How does Python compare to languages like Java or C++?
Answer
Python trades raw execution speed and compile-time type safety for development speed, readability, and flexibility. Java and C++ are statically typed and generally faster; Python is dynamically typed and optimizes for how quickly you can write and change code.
This question tests whether you understand trade-offs rather than treating one language as universally "better."
Key points
- 1Typing — Python: Dynamic; Java: Static; C++: Static
- 2Execution — Python: Interpreted (bytecode + VM); Java: Compiled to bytecode, JIT-run on JVM; C++: Compiled to native machine code
- 3Memory management — Python: Automatic (GC); Java: Automatic (GC); C++: Manual (or RAII/smart pointers)
- 4Typical speed — Python: Slower; Java: Fast; C++: Fastest
- 5Verbosity — Python: Low; Java: Medium; C++: High
- 6Common use cases — Python: Scripting, data science, ML, web backends; Java: Enterprise apps, Android; C++: Systems, games, performance-critical code
Example
# Python: no type declarations, no semicolons, no braces def add(a, b): return a + b
💡 A strong answer ends with "it depends on the use case" — e.g., you'd reach for C++ for a game engine's render loop, but Python for a data pipeline or an internal tool where developer velocity matters more than raw speed.
Is Python interpreted or compiled?
Answer
Python is both, in a sense: source code is first compiled to platform-independent bytecode (.pyc files), and that bytecode is then interpreted by the Python Virtual Machine (PVM) at runtime. There's no separate "compile" step the developer has to run manually.
Calling Python simply "interpreted" is an oversimplification that experienced interviewers will probe. The real pipeline is: 1. Your.py source is parsed and compiled into bytecode (instructions for the PVM), cached in __pycache__ as.pyc files. 2. The PVM executes that bytecode line by line, which is what people mean by "interpreted." 3.
This differs from C/C++, where a compiler produces native machine code ahead of time, and from Java, which compiles to JVM bytecode and can further JIT-compile hot paths to machine code. CPython (the standard implementation) does not JIT-compile by default, which is one reason it's slower than Java's JVM for CPU-bound work. PyPy is an alternative implementation that does use a JIT compiler.
Example
import py_compile py_compile.compile("greet.py") # Produces bytecode you can inspect, e.g. under __pycache__/greet.cpython-312.pyc
💡 Say "compiled to bytecode, then interpreted by a virtual machine" instead of a flat "interpreted." That single phrase signals real understanding of the execution model.
What is dynamic typing in Python?
Answer
Dynamic typing means variable types are determined and checked at runtime, not declared ahead of time. The same variable name can be rebound to values of different types over its lifetime.
In statically typed languages (Java, C++), you declare a variable's type once, and the compiler enforces it. In Python, a variable is just a name bound to an object, and that object carries its own type — the name itself has no fixed type. This gives flexibility but pushes type-related errors from compile time to runtime.
Python is also strongly typed, which is a separate axis from dynamic/static: it won't silently coerce incompatible types (e.g., "2" + 2 raises a TypeError), unlike a weakly typed language such as JavaScript.
Example
x = 5 # x refers to an int print(type(x)) # <class 'int'> x = "five" # now x refers to a str — perfectly legal print(type(x)) # <class 'str'> "2" + 2 # TypeError: strongly typed, no implicit coercion
💡 Interviewers often expect you to distinguish "dynamically typed" from "weakly typed." Python is dynamic and strong — mixing those two ideas up is a common giveaway of a shallow understanding.
How do you declare and assign variables in Python?
Answer
There's no separate declaration step — assignment with = both creates the name and binds it to a value. Python infers the type from the assigned object.
A Python "variable" is really a reference (a name in a namespace) pointing to an object in memory. Assignment binds a name to an object; it doesn't copy the object into a fixed-size box the way C does. Python supports several convenient assignment forms: multiple assignment, chained assignment, and tuple unpacking.
Example
x = 10 # simple assignment a, b, c = 1, 2, 3 # multiple assignment via unpacking x = y = z = 0 # chained assignment — all three bind to the same object first, *rest = [1, 2, 3, 4] # starred unpacking: first=1, rest=[2, 3, 4]
💡 Mention that assignment binds a name to an object rather than copying data — this is the foundation for later questions about mutability, is vs ==, and function argument passing.
What are Python's built-in data types?
Answer
Python's core built-in types fall into a few families: numeric (int, float, complex), sequence (str, list, tuple, range), mapping (dict), set types (set, frozenset), boolean (bool), and NoneType.
A well-organized answer groups types by category rather than listing them randomly: Everything in Python is an object, including functions, classes, and modules — even int and type are objects of type type.
Key points
- 1Numeric — Types: int, float, complex; Mutable?: No
- 2Boolean — Types: bool (subclass of int); Mutable?: No
- 3Sequence — Types: str, list, tuple, range; Mutable?: list yes; others no
- 4Mapping — Types: dict; Mutable?: Yes
- 5Set — Types: set, frozenset; Mutable?: set yes; frozenset no
- 6Special — Types: NoneType; Mutable?: No
Example
values = [42, 3.14, "text", (1, 2), [1, 2], {1, 2}, {"k": "v"}, True, None] for v in values: print(type(v).__name__, "->", v)
💡 Bring up mutability while listing types — it previews Q8 and shows you're not just memorizing a list.
What is the difference between mutable and immutable objects?
Answer
A mutable object's contents can be changed after creation without changing its identity (e.g., list, dict, set). An immutable object's value can never change once created — any "modification" actually creates a new object (e.g., int, str, tuple, frozenset).
This distinction affects far more than trivia — it determines whether an object can be a dictionary key (must be hashable, which usually means immutable), whether passing it into a function can produce side effects the caller sees, and whether += mutates in place or rebinds. key)? "modification"
Key points
- 1Examples — Mutable: list, dict, set, custom classes by default; Immutable: int, float, str, tuple, frozenset, bytes
- 2Can change in place? — Mutable: Yes; Immutable: No — any change creates a new object
- 3Hashable (usable as dict — Mutable: Generally no; Immutable: Generally yes
- 4id() after — Mutable: Same; Immutable: Different
Example
# Mutable: identity stays the same lst = [1, 2, 3] original_id = id(lst) lst.append(4) print(id(lst) == original_id) # True — same object, changed in place # Immutable: "modifying" creates a new object s = "hello" original_id = id(s) s += " world" print(id(s) == original_id) # False — s now points to a brand-new str
What is the difference between is and ==?
Answer
== compares values (calls __eq__), while is compares identity — whether two names point to the exact same object in memory (equivalent to comparing id(a) == id(b)).
Two distinct objects can be equal in value but not identical, e.g. two separate lists containing [1, 2, 3]. Conversely, two names can be identical (is) while comparing equal for the trivial reason that they're the same object. is should be reserved for singleton comparisons — most idiomatically x is None, x is True, x is False — never for general value comparison. == is
Key points
- 1Compares — Value (via __eq__); Identity (memory address)
- 2Overridable? — Yes, by defining __eq__; No
- 3Typical use — Comparing data; Comparing to None, True, False, sentinels
Example
a = [1, 2, 3] b = [1, 2, 3] print(a == b) # True -> same value print(a is b) # False -> different objects in memory c = a print(a is c) # True -> c is literally the same object as a
What is type conversion in Python?
Answer
Type conversion is changing a value from one type to another. Python supports implicit conversion (done automatically by the interpreter, only between compatible numeric types) and explicit conversion (done manually by the programmer using functions like int(), str(), float()).
Implicit conversion in Python is deliberately limited compared to weakly typed languages — it only happens to avoid losing information, such as promoting an int to a float in a mixed arithmetic expression. It will never silently convert a str to a number, which is why "2" + 2 raises TypeError rather than guessing your intent.
Example
# Implicit conversion: int is promoted to float automatically result = 5 + 2.0 # 7.0 (int widened to float) # Explicit conversion: the programmer decides age_str = "25" age_int = int(age_str) # 25 price = str(19.99) # "19.99" flag = bool(0) # False
💡 Point out that explicit conversion can raise exceptions (int("abc") raises ValueError) — this naturally leads into a discussion of validating external input, which interviewers like to hear.
Why does Python use indentation instead of braces?
Answer
Python uses indentation to define code blocks (instead of {} or begin/end) to enforce readable, visually consistent code — the way code looks is the way it behaves, which eliminates a whole class of "the braces don't match the indentation" bugs.
This is called the "off-side rule." Indentation isn't just a style convention in Python — it's syntactically significant. A block (the body of a function, loop, conditional, class, etc.) is defined by a consistent indentation level; mixing tabs and spaces, or indenting inconsistently, raises an IndentationError. Most style guides (PEP 8) recommend 4 spaces per indentation level and never mixing tabs with spaces.
Example
def check_number(n): if n > 0: print("positive") elif n < 0: print("negative") else: print("zero")
💡 Mention IndentationError and the tabs/spaces trap explicitly — it shows you've actually hit this in practice, not just read about it.
How do you write comments and docstrings in Python?
Answer
Single-line comments start with #. Multi-line explanatory text is usually written as consecutive # lines or, for documenting modules/classes/functions specifically, as a docstring — a string literal (often triple-quoted) placed immediately after the definition, accessible via.__doc__.
Comments and docstrings serve different purposes: comments explain why code does something to future readers of the source; docstrings are structured documentation meant to be read by tools (help(), IDEs, Sphinx) and other developers who may never open the source file.
Example
# This is a single-line comment explaining the next statement total = price * quantity # inline comment def add(a, b): """Return the sum of a and b. Args: a (int): first number b (int): second number Returns: int: the sum """ return a + b print(add.__doc__)
💡 Mention that Python has no true multi-line comment syntax — a triple-quoted string used midfunction is just an unused string literal, not an official comment, though it's commonly used that way.
What are keywords and identifiers in Python?
Answer
Keywords are reserved words with fixed meaning in the language (if, for, class, import, etc.) that cannot be used as variable names. Identifiers are the names programmers choose for variables, functions, classes, and modules, and must follow specific naming rules.
Identifier rules: must start with a letter or underscore (not a digit), can contain letters, digits, and underscores, and are case-sensitive (Age and age are different names). You can check whether a string is a reserved keyword using the keyword module rather than memorizing the full list.
Example
import keyword print(keyword.iskeyword("class")) # True print(keyword.iskeyword("classes")) # False # Valid identifiers user_name = "Ana" _private = 42 value2 = 10 # Invalid: 2value = 10 -> SyntaxError, cannot start with a digit
💡 Bring up soft keywords (like match, case, _ introduced in Python 3.10 for structural pattern matching) if the role expects modern Python — it signals you keep up with the language.
What are the main types of operators in Python?
Answer
Python groups operators into arithmetic, comparison, logical, assignment, bitwise, membership (in, not in), and identity (is, is not) operators.
Category Examples Two operators worth calling out specifically because they trip up newcomers: / always returns a float (true division), while // performs floor division and returns an int when both operands are int.
Key points
- 1Comparison — + - * / // % **: ==!= > < >= <=
- 2Logical — + - * / // % **: and or not
- 3Assignment — + - * / // % **: = += -= *= /= //= **= %=
- 4Bitwise — + - * / // % **: & \| ^ ~ << >>
- 5Membership — + - * / // % **: in, not in
- 6Identity — + - * / // % **: is, is not
Example
print(7 / 2) # 3.5 (true division) print(7 // 2) # 3 (floor division) print(7 % 2) # 1 (modulo) print(2 ** 10) # 1024 (exponentiation) print(3 in [1, 2, 3]) # True (membership) print(None is not False) # True (identity)
💡 Being asked to explain // vs / is common precisely because many candidates from other languages assume / does integer division like C or Java.
How do input and output work in Python?
Answer
input() reads a line of text from standard input and always returns a str (you must convert it explicitly if you need a number). print() writes to standard output and accepts multiple arguments plus keyword arguments like sep and end to control formatting.
A common beginner mistake is forgetting that input() always returns a string, so arithmetic on unconverted input raises a TypeError. print() 's sep (default " ") and end (default "\n") parameters are frequently used to control output formatting without manual string concatenation.
Example
age = input("Enter your age: ") # returns a str, e.g. "25" age = int(age) # must convert explicitly for math print("a", "b", "c", sep="-") # a-b-c print("Loading", end="...") # no trailing newline print("done") # Loading...done
💡 Mention f-strings (f"{name} is {age}") as the modern, preferred way to format output over % formatting or.format() — it signals familiarity with current idiomatic Python (3.6+).
What is None, and how is it different from 0, False, or an empty string?
Answer
None is Python's singleton representing "no value" or "nothing here" — it is its own type (NoneType) and is distinct from 0, False, or "", even though all four are "falsy" in a boolean context.
None is commonly used as a default placeholder (e.g., a default function argument, or the return value of a function with no explicit return). It is a true singleton — there is exactly one None object in a running program — which is why identity checks against it (x is None) are both correct and idiomatic, unlike checks against other falsy values.
Example
def get_user(user_id): if user_id not in database: return None # "no user found," distinct from an empty result return database[user_id] result = get_user(999) if result is None: # correct: identity check against the singleton print("User not found") print(None == False) # False -- different values entirely print(bool(None)) # False -- but both are falsy in a boolean context
What are truthy and falsy values in Python?
Answer
Every object in Python has an implicit boolean value used in conditions. "Falsy" values evaluate to False in a boolean context — this includes False, None, 0, 0.0, empty strings, and empty collections ([], {}, (), set()). Everything else is "truthy."
This lets you write if my_list: instead of if len(my_list) > 0:, which is considered more Pythonic. Custom classes can control their own truthiness by implementing __bool__ (or, if absent, Python falls back to __len__, treating a length of 0 as falsy).
Example
falsy_values = [False, None, 0, 0.0, "", [], {}, (), set()] print(all(not bool(v) for v in falsy_values)) # True class Cart: def __init__(self): self.items = [] def __len__(self): return len(self.items) cart = Cart() if not cart: # falls back to __len__() == 0 -> True (empty) print("Cart is empty")
💡 Bringing up the __bool__ / __len__ fallback for custom objects is a strong signal you understand Python's data model, not just built-in types.
What is scope in Python?
Answer
Scope defines where in your code a name (variable, function, class) is visible and accessible. Python resolves names using the LEGB rule: Local, Enclosing, Global, Built-in — searched in that order.
Unlike some languages, Python does not create a new scope for every code block (if, for, while) — only functions, classes (partially), lambdas, comprehensions, and modules introduce new scopes. This means a variable assigned inside an if block is still visible after the block, as long as it's within the same function or module.
Example
x = "global" def outer(): x = "enclosing" def inner(): x = "local" print(x) # "local" -- found immediately, no need to look further inner() print(x) # "enclosing" outer() print(x) # "global"
💡 This question is almost always a setup for Q19 (LEGB) — answer it briefly and let the LEGB question carry the depth.
Explain the LEGB rule in detail.
Answer
LEGB describes the order Python searches for a name: Local (current function) → Enclosing (any outer function, for closures) → Global (module level) → Built-in (Python's built-in namespace, like len or print). Python stops at the first scope where the name is found.
A common misconception: simply reading an outer variable requires no special keyword. But assigning to a name inside a function makes Python treat it as local for that entire function unless you explicitly declare global or nonlocal — this is what causes UnboundLocalError (see Q20).
Key points
- 1Local — lives inside the current function; a variable assigned inside def f()
- 2Enclosing — an outer (non-global) function, for nested functions and closures; a variable in outer() referenced by inner()
- 3Global — the top level of the module; a variable assigned outside any function
- 4Built-in — Python's builtins module; len, print, Exception
Example
count = 0 # global def make_counter(): total = 0 # enclosing, relative to increment() def increment(): nonlocal total # without this, "total += 1" would raise UnboundLocalError total += 1 return total return increment counter = make_counter() print(counter()) # 1 print(counter()) # 2 print(len) # built-in, found only after L, E, G all fail
💡 Walk through LEGB with a nested-function example rather than a definition — interviewers want to see you trace name resolution, not recite an acronym.
What is the difference between global and local variables, and what do global / nonlocal do?
Answer
A local variable is defined inside a function and only exists during that call; a global variable is defined at module level and exists for the program's lifetime. The global keyword lets a function assign to a global name instead of creating a new local one; nonlocal does the same for a name in an enclosing (not global) function scope.
Python only needs global / nonlocal when you intend to reassign an outer variable — reading it requires nothing special. If you assign to a name anywhere in a function body without declaring it global / nonlocal, Python treats that name as local for the entire function, even before the assignment line — which produces the classic UnboundLocalError.
Example
counter = 0 def increment_broken(): counter += 1 # UnboundLocalError: counter referenced before assignment # (Python sees the assignment and treats counter as local) def increment_fixed(): global counter counter += 1 # now correctly refers to the module-level variable
How does Python manage memory?
Answer
Python manages memory automatically using reference counting as the primary mechanism, backed by a cyclic garbage collector that detects and cleans up reference cycles that reference counting alone can't free.
Every object keeps a count of how many references point to it. When that count hits zero, CPython deallocates the object immediately. This is fast and deterministic but can't reclaim objects that reference each other in a cycle (e.g., two objects each holding a reference to the other) since their counts never reach zero on their own. The gc module periodically scans for such cycles and collects them.
This topic goes much deeper in (Advanced Python) — for a fundamentals-level answer, reference counting + cyclic GC is enough.
Example
import sys a = [] print(sys.getrefcount(a)) # baseline count (includes the temporary arg reference) b = a print(sys.getrefcount(a)) # increased -- another name points to the same list del b print(sys.getrefcount(a)) # decreased again
💡 Mentioning "reference counting plus a cyclic garbage collector" (not just "garbage collection") shows depth. Save __slots__, generational GC, and the memory pool allocator (pymalloc) details for if asked to go deeper.
What is PEP 8, and why does it matter?
Answer
PEP 8 is Python's official style guide, defining conventions for naming, indentation, line length, whitespace, and code layout. Following it makes code more consistent and readable across teams and projects.
Key conventions include: 4 spaces per indentation level (no tabs), snake_case for functions and variables, PascalCase for classes, UPPER_SNAKE_CASE for constants, a maximum line length of 79–99 characters depending on project convention, and two blank lines between top-level function/class definitions.
Tools like flake8, pylint, and formatters like black or ruff format automate PEP 8 compliance so teams don't have to enforce it manually in code review.
Example
# PEP 8 compliant MAX_RETRIES = 3 class HttpClient: def send_request(self, url): pass # Not PEP 8 compliant max_retries = 3 class HttpClient: def send_request(self, url): pass
💡 Mention a formatter/linter you've actually used (black, ruff, flake8) — it signals real project experience, not just textbook knowledge.
What are the key differences between Python 2 and Python 3?
Answer
Python 3 is the actively maintained version of the language; Python 2 reached end-of-life in January 2020. The most cited differences are print being a function (not a statement), / performing true division by default, and native strings being Unicode rather than bytes.
For an interview, the practical takeaway is simpler than the historical trivia: all new code should be Python 3, and this question is mostly relevant when discussing legacy codebases or migrations.
Key points
- 1print — Python 2: a statement, print "hi"; Python 3: a function, print("hi")
- 2Division — Python 2: 5 / 2 == 2 (integer division); Python 3: 5 / 2 == 2.5 (true division)
- 3Strings — Python 2: str is bytes by default; Python 3: str is Unicode and bytes is separate
- 4input() — Python 2: input() evaluates the string, raw_input() returns it; Python 3: input() always returns str
- 5Maintenance — Python 2: end-of-life since January 2020; Python 3: actively developed
Example
# Python 3 only — this is what modern code should look like print("Result:", 5 / 2) # Result: 2.5
💡 Keep this answer brief unless the role explicitly involves legacy migration work — dwelling on Python 2 in 2026 can read as outdated knowledge rather than depth.
What are the rules for naming identifiers in Python?
Answer
An identifier must start with a letter (A–Z, a–z) or an underscore, followed by any combination of letters, digits, and underscores. Identifiers are case-sensitive and cannot be a reserved keyword.
Beyond the hard syntax rules, PEP 8 layers on style conventions: snake_case for variables and functions, PascalCase for classes, UPPER_SNAKE_CASE for constants, and a leading underscore (_name) as a convention (not enforcement) for "internal use" attributes.
A leading double underscore (__name) triggers name mangling inside classes, which is different from a stylistic convention — it actually changes how the attribute is stored.
Example
valid_name = 1 _private = 2 __mangled = 3 # inside a class, becomes _ClassName__mangled CONSTANT_VALUE = 100 class Example: pass # PascalCase for class names # 2fast = 5 # SyntaxError -- cannot start with a digit # class = 5 # SyntaxError -- 'class' is a reserved keyword
💡 Distinguishing "single underscore = convention" from "double underscore = actual name mangling" is a good depth signal — many candidates think both are purely stylistic.
What is the difference between a script and a module in Python?
Answer
Any.py file is technically a module, but it's called a script when it's meant to be run directly (as the program's entry point) and a module when it's meant to be imported and reused by other files.
The distinction is about intent and usage, not syntax. Python sets a special variable, __name__, to "__main__" when a file is executed directly, and to the module's actual name when it's imported. This is why the if __name__ == "__main__": guard is idiomatic: it lets a file work as both — reusable when imported, runnable when executed directly — without the import triggering unwanted side effects.
Example
# file: mathutils.py def add(a, b): return a + b if __name__ == "__main__": # Only runs when this file is executed directly, # e.g. `python mathutils.py` -- NOT when it's imported elsewhere. print(add(2, 3)) # file: main.py import mathutils print(mathutils.add(10, 20)) # add() runs; the __main__ block in mathutils.py does not
💡 This question is really testing whether you understand __name__ == "__main__", which shows up constantly in real codebases (CLI tools, test entry points) — always tie the answer back to that idiom.
Recommended resourcesAffiliate links · may earn us a commission