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 →
- 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 - What is the difference between remove(), pop() and del for a list?
remove(x) deletes the first item equal to x. pop(i) deletes the item at index i (default last) and returns it. del lst[i] or del lst[a:b] deletes by index or slice and returns nothing.
BeginnerQuick answer1 min read - What is the difference between type() and isinstance() in Python?
type(x) returns the exact class of x, so comparing with == ignores inheritance. isinstance(x, C) is True if x is an instance of C or of any subclass of C, so it is the usual choice for type checks.
BeginnerQuick answer1 min read - What is the LEGB rule in Python?
LEGB is the order in which Python looks up a name: Local, Enclosing (outer functions), Global (module), then Built-in. The first scope that contains the name wins, and if none do, Python raises NameError.
BeginnerQuick answer1 min read - Why do we use the with statement when working with files?
with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().
BeginnerQuick answer1 min read - Why does 0.1 + 0.2 == 0.3 return False in Python, and how do you compare floats correctly?
Floats are stored in binary, and 0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004. Compare floats with math.isclose(), or use decimal.Decimal when exact decimal arithmetic is needed, such as for money.
BeginnerQuick answer1 min read - Why is (5) not a tuple in Python, and how do you create a one-element tuple?
Parentheses alone only group an expression, so (5) is just the integer 5. The comma makes the tuple, so a one-element tuple is written (5,) or 5,. The empty tuple is ().
BeginnerQuick answer1 min read - Write a function that reverses a string in Python.
The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.
BeginnerQuick answerCoding1 min read - Write a function to check whether a string is a palindrome, ignoring case and non-letters.
Clean the string by keeping only letters and digits in lowercase, then compare it with its reverse. This runs in O(n) time. A two-pointer version avoids the extra reversed copy.
BeginnerQuick answerCoding1 min read - Write a function to check whether two strings are anagrams of each other.
Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.
BeginnerQuick answerCoding1 min read - Write a function to flatten a list of lists into a single list.
For one level of nesting, use a nested comprehension: [x for row in rows for x in row]. For arbitrary depth, use recursion and check isinstance(item, list). The flat version is O(n) in the number of elements.
BeginnerQuick answerCoding1 min read - Write a function to remove duplicates from a list while keeping the original order.
Walk through the list, keep a set of items already seen, and add an item to the result only if it is not in the set. This is O(n) time. Using set(lst) alone is fast but loses the order.
BeginnerQuick answerCoding1 min read - Write a generator that yields the first n Fibonacci numbers.
Keep two variables a and b, yield a, then update them with a, b = b, a + b, repeating n times. The generator produces one value at a time, uses O(1) memory and does O(n) additions in total.
BeginnerQuick answerCoding1 min read - Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?
No. In Python 3 a comprehension has its own scope, so its loop variable does not leak. A normal for loop does leave its variable behind. In Python 2, list comprehensions did leak.
IntermediateQuick answer1 min read - How do you make your own class work with +, len() and indexing in Python?
Implement the matching dunder methods: __add__ for +, __len__ for len(), and __getitem__ for obj[i]. Python translates the syntax into calls to these methods, so no inheritance from built-in types is needed.
IntermediateQuick answer1 min read - How do you read a very large file in Python without loading it all into memory?
Iterate over the file object directly with for line in f. It reads one line at a time through a buffer, so memory use stays small. read() and readlines() load everything at once and can exhaust memory on big files.
IntermediateQuick answer1 min read - How do you write your own context manager in Python?
Either write a class with __enter__ and __exit__ methods, or write a generator function decorated with @contextlib.contextmanager that yields once. Code before the yield is setup and code after it is cleanup, which should sit in a finally block.
IntermediateQuick answer1 min read - How does a for loop work under the hood in Python?
A for loop calls iter() on the object to get an iterator, then repeatedly calls next() on it, running the body each time. When next() raises StopIteration, the loop ends quietly.
IntermediateQuick answer1 min read - How does Python find a module when you write import?
Python checks sys.modules for an already-loaded copy, then searches the directories in sys.path in order: the script's folder, PYTHONPATH entries, the standard library and site-packages. The first match wins, which is why a local file can shadow a library.
IntermediateQuick answer1 min read - What are Decimal and Fraction in Python, and when would you use them instead of float?
Decimal does exact base-10 arithmetic, which suits money. Fraction stores a ratio of two integers and gives exact results for things like 1/3. Both avoid the binary rounding errors of float, at the cost of speed.
IntermediateQuick answer1 min read - What do the / and * markers in a Python function signature mean?
Parameters before / are positional-only, so callers cannot pass them by name. Parameters after a bare * are keyword-only, so callers must pass them by name. Both make an API clearer and safer to change.
IntermediateQuick answer1 min read - What does "from module import *" do, and what is __all__?
import * brings every public name of a module into your namespace, which can silently overwrite existing names. A module can control what it exports by defining __all__, a list of names. Without __all__, names starting with an underscore are skipped.
IntermediateQuick answer1 min read - What does super() do in Python, and why call super().__init__()?
super() returns a proxy that looks up methods on the next class in the MRO. Calling super().__init__() runs the parent's initialiser so the inherited setup is not skipped. If a child defines __init__ and does not call it, the parent's attributes are never created.
IntermediateQuick answer1 min read