Interview Questions
Lists · Study material
Lists – Interview Questions
1. What is the difference between append() and extend()?
append(x) adds x as a single item (a list becomes a nested list); extend(iterable) adds each item.
2. Difference between sort() and sorted()?
sort() is a list method that sorts in place and returns None; sorted() takes any iterable and returns a new list.
3. Difference between remove(), pop() and del?
remove(x) deletes the first item equal to x; pop(i) deletes and returns the item at index i; del lst[i] or del lst[a:b] deletes by index or slice.
4. Why does [[0] * 3] * 3 behave strangely?
The outer * repeats a reference to the same inner list, so all rows are one object.
5. How do you copy a list?
Shallow: copy(), list(lst), lst[:]. Deep: copy.deepcopy(lst).
6. What is the time complexity of common list operations?
Index, append, pop() at the end: O(1). insert, remove, pop(0), in: O(n). sort: O(n log n).
7. Is Python's sort stable?
Yes (Timsort); equal keys keep their relative order.
8. How do you reverse a list?
lst.reverse() in place, lst[::-1] for a new list, reversed(lst) for an iterator.
9. What does lst * 3 do?
Builds a new list with the items repeated three times (references, not copies).
10. Difference between a += [x] and a = a + [x]?
+= extends the same list in place; + creates a new list and rebinds a.
11. How do you find the index of an item?
lst.index(x) – raises ValueError if absent; use enumerate for all positions.
12. How do you remove duplicates while keeping order?
list(dict.fromkeys(lst)).
13. Can a list contain itself?
Yes: a.append(a) works and prints as [[...]].
14. What does max(lst, key=len) do?
Returns the item whose len() is largest (the first one on ties).
15. How do you flatten a list of lists?
[x for row in rows for x in row], or itertools.chain.from_iterable(rows).