Lists
List Methods
append, extend, insert, remove, pop, sort
Interview: Essential methods — tests understanding of in-place vs returning-new-list operations
Python lists provide a rich set of methods for adding, removing, searching, and rearranging elements. A critical distinction is whether methods modify the list in place (returning None) or return a new list.
Adding Elements
- append(x): Add single element to end — O(1) amortized
- extend(iterable): Add all elements from iterable to end — O(k) where k is length of iterable
- insert(i, x): Insert element at index i — O(n) because elements must shift
Removing Elements
- remove(x): Remove first occurrence of value x — O(n). Raises ValueError if not found
- pop([i]): Remove and return element at index i (default: last) — O(1) for last, O(n) for arbitrary
- clear(): Remove all elements — O(n)
- del lst[i]: Delete by index (not a method, but common)
Searching and Counting
- index(x, [start], [end]): Find index of first occurrence — O(n). Raises ValueError if not found
- count(x): Count occurrences of x — O(n)
Sorting and Reversing
- sort(key=None, reverse=False): In-place sort using Timsort — O(n log n). Returns None!
- reverse(): In-place reversal — O(n). Returns None!
- sorted() vs sort():
sorted()returns a new list;.sort()modifies in place - Custom sorting:
lst.sort(key=lambda x: x.age)— sort by attribute
Common Pitfall
lst.sort() and lst.reverse() return None. Writing result = lst.sort() gives you None, not a sorted list. This is a deliberate design choice: it signals that the operation modifies in place.
Use Cases
Implementing stacks (append/pop) and queues (deque)
Data cleaning: removing duplicates, sorting, filtering
Priority queues with sorted insertion
Building result collections with append in loops
Common Mistakes
Assigning result of sort()/reverse() to a variable — they return None
Using remove() without checking if item exists (raises ValueError)
Using pop(0) for queues — O(n); use collections.deque instead
Confusing append([1,2]) with extend([1,2]) — append adds the list as one element