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 a list and a tuple in Python?
A list is mutable, so you can add, remove or change items after creating it. A tuple is immutable, so its contents are fixed once created. Tuples are slightly lighter and can be used as dictionary keys if all their items are hashable; lists cannot.
BeginnerIn-depth3 min read - What is the difference between a shallow copy and a deep copy in Python?
A shallow copy creates a new outer container but keeps references to the same inner objects, so changing a nested list affects both. A deep copy recursively copies everything inside, so the two are fully independent. Use copy.copy() for shallow and copy.deepcopy() for deep.
BeginnerIn-depth3 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 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 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 - 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