Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- Are strings mutable in Python, and how do you change a character in one?
Strings are immutable, so s[0] = "x" raises TypeError. To change one, build a new string using slicing, replace(), or join over a list of characters.
BeginnerQuick answer1 min read - How do dictionary and set comprehensions work in Python?
A dict comprehension uses curly braces with key: value, as in {k: v for ...}. A set comprehension uses curly braces with one expression, as in {x for ...}, and removes duplicates automatically.
BeginnerQuick answer1 min read - How do try, except, else and finally work together in Python?
try holds the risky code, except handles an error, else runs only if no exception occurred, and finally always runs, whether or not there was an error. Use else for code that depends on the try succeeding.
BeginnerQuick answer1 min read - How do you create and raise a custom exception in Python?
Subclass Exception (not BaseException), give it a clear name ending in Error, and raise it with raise. Add attributes or a message in __init__ if callers need details. A shared base class lets callers catch a whole family.
BeginnerQuick answer1 min read - How do you merge two dictionaries in Python?
Use d1 | d2 in Python 3.9+, or {**d1, **d2} in older versions, or d1.update(d2) to modify d1 in place. When both have the same key, the value from the right-hand dictionary wins.
BeginnerQuick answer1 min read - How do you read and write JSON in Python?
Use the json module: json.dumps and json.loads convert between Python objects and JSON strings, while json.dump and json.load do the same with file objects. JSON null becomes None, and keys always become strings.
BeginnerQuick answer1 min read - How do you swap two variables in Python without a temporary variable?
Use tuple unpacking: a, b = b, a. The right side is evaluated into a tuple first, then assigned to the names on the left, so no temporary variable is needed.
BeginnerQuick answer1 min read - How does string slicing work in Python, and what do negative indices mean?
s[start:stop:step] takes characters from start up to but not including stop. Negative indices count from the end, so s[-1] is the last character. Out-of-range slice bounds are clamped and never raise an error.
BeginnerQuick answer1 min read - In a list comprehension, where does the if go: before or after the for?
A filter if goes after the for clause and drops items. An if-else that chooses between two values is an expression, so it goes before the for. Writing else after the for is a SyntaxError.
BeginnerQuick answer1 min read - Is Python statically or dynamically typed, and is it strongly or weakly typed?
Python is dynamically typed, because types are checked at runtime and a name can point to any object. It is also strongly typed, because it will not silently mix incompatible types, so "5" + 5 raises TypeError.
BeginnerQuick answer1 min read - Is there a maximum value for an int in Python?
No. Python 3 integers have arbitrary precision: they grow to use as much memory as the value needs, so they never overflow. sys.maxsize is only the largest index a container can have, not the largest int. Floats, by contrast, are 64-bit and do overflow to inf.
BeginnerQuick answer1 min read - What are the common file modes in Python's open() function?
r" reads (default), "w" writes and erases existing content, "a" appends to the end, and "x" creates a new file and fails if it exists. Adding "+" allows both read and write, and "b" means binary instead of text.
BeginnerQuick answer1 min read - What are the common set operations in Python, and what is a frozenset?
Sets support union (|), intersection (&), difference (-) and symmetric difference (^). A set holds unique, hashable items with fast membership tests. A frozenset is an immutable set, so it can be a dict key or a set element.
BeginnerQuick answer1 min read - What are the different ways to format strings in Python, and which should you prefer?
Python has % formatting, str.format() and f-strings. Prefer f-strings (3.6+): they are the most readable and usually the fastest, because expressions are written directly inside the string.
BeginnerQuick answer1 min read - What are the main built-in data types in Python?
Numbers (int, float, complex, bool), text (str), sequences (list, tuple, range), mappings (dict), sets (set, frozenset), bytes types and NoneType. Lists, dicts and sets are mutable; the rest are immutable.
BeginnerQuick answer1 min read - What are truthy and falsy values in Python?
Every object has a truth value when used in an if or while. Falsy values are False, None, zero of any numeric type, and empty containers such as '', [], (), {}, set() and range(0). Everything else is truthy unless its class defines __bool__ or __len__ to say otherwise.
BeginnerQuick answer1 min read - What does if __name__ == "__main__" do in a Python script?
When a file runs directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name instead. The if-check lets a file run some code only when executed as a script, not when imported.
BeginnerQuick answer1 min read - What does range() return in Python 3, and is it a list?
range() returns a lazy range object, not a list. It stores only start, stop and step, so range(10**9) takes tiny memory, supports indexing, len() and the in operator, and produces numbers only when asked.
BeginnerQuick answer1 min read - What does the assert statement do, and when should you not use it?
assert condition, message raises AssertionError if the condition is false. It is for internal sanity checks during development. Do not use it to validate user input, because assertions are removed when Python runs with the -O flag.
BeginnerQuick answer1 min read - What is a lambda function in Python, and what are its limits?
A lambda is a small anonymous function written as lambda args: expression. It contains a single expression, returns its value automatically and cannot hold statements. It is handy as a short key or callback.
BeginnerQuick answer1 min read - What is a list comprehension in Python, and when should you use one?
A list comprehension builds a list in one expression: [expr for item in iterable if condition]. It is shorter and usually faster than an append loop. Use it for simple transform-and-filter work, not for complicated logic.
BeginnerQuick answer1 min read - What is None in Python and how is it different from 0, False or an empty string?
None is a special singleton object of type NoneType that means no value. It is falsy like 0, False and '', but it is not equal to any of them. Functions without a return statement return None, and you should test for it with is None.
BeginnerQuick answer1 min read - What is the difference between __str__ and __repr__ in Python?
__str__ gives a readable description meant for users and is used by print() and str(). __repr__ gives an unambiguous description meant for developers, ideally looking like code that recreates the object. If only __repr__ exists, print falls back to it.
BeginnerQuick answer1 min read - What is the difference between /, // and % in Python, especially with negative numbers?
/ is true division and always returns a float. // is floor division: it rounds down toward negative infinity. % returns the remainder that matches floor division, so the result takes the sign of the divisor. For example -7 // 2 is -4 and -7 % 2 is 1.
BeginnerQuick answer1 min read - What is the difference between a module and a package in Python?
A module is a single .py file. A package is a directory of modules, normally with an __init__.py file, that you import using dotted names like shop.billing. Packages let you organise a large project into a hierarchy.
BeginnerQuick answer1 min read - What is the difference between an iterable and an iterator in Python?
An iterable can produce an iterator when you call iter() on it, such as a list or string. An iterator is the object that actually hands out items one at a time through next() and remembers its position. Iterators are single-use.
BeginnerQuick answer1 min read - What is the difference between append(), extend() and insert() on a list?
append(x) adds x as one item at the end. extend(iterable) adds each element of the iterable at the end. insert(i, x) puts x at position i and shifts later items right, which costs O(n).
BeginnerQuick answer1 min read - What is the difference between dict[key], dict.get(key) and dict.setdefault(key, default)?
d[key] raises KeyError if the key is missing. d.get(key, default) returns the default without changing the dict. d.setdefault(key, default) returns the value and also inserts the default if the key was missing.
BeginnerQuick answer1 min read - What is the difference between is and == in Python?
== checks whether two objects have equal values, using __eq__. is checks whether two names point to the very same object in memory, by comparing identity. Use is only for singletons like None.
BeginnerQuick answer1 min read - What is the difference between list.sort() and sorted() in Python?
list.sort() sorts the list in place and returns None. sorted() accepts any iterable, leaves the original unchanged and returns a new sorted list. Both are stable and accept key and reverse arguments.
BeginnerQuick answer1 min read