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 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