Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What are some commonly used list methods?
What you need to know
The methods, with what they return
1nums = [3, 1, 2]2nums.append(4) # [3, 1, 2, 4]3nums.extend([5, 6]) # [3, 1, 2, 4, 5, 6]4nums.insert(0, 9) # [9, 3, 1, 2, 4, 5, 6]5nums.remove(1) # [9, 3, 2, 4, 5, 6] first matching VALUE6print(nums.pop()) # 6 -> removes and returns the last item7print(nums.pop(0)) # 9 -> or the item at an index8print(nums) # [3, 2, 4, 5]9print(nums.index(2), nums.count(2)) # 1 110result = nums.sort()11print(result, nums) # None [2, 3, 4, 5] -> sorted in place, returns None12nums.reverse()13print(nums) # [5, 4, 3, 2]| Method | Changes the list? | Returns | Cost |
|---|---|---|---|
append(x) | yes | None | O(1) |
extend(it) | yes | None | O(k) for k new items |
insert(i, x) | yes | None | O(n) |
remove(x) | yes | None (ValueError if missing) | O(n) |
pop() / pop(i) | yes | the item | O(1) at end, O(n) elsewhere |
index(x), count(x) | no | int | O(n) |
sort(), reverse() | yes | None | O(n log n), O(n) |
copy() | no | new list | O(n) |
Why the front of a list is slow
A Python list is a dynamic array: items sit in one continuous block of memory. Adding at the end just fills the next slot (Python keeps spare room, so this is O(1) on average). Inserting or removing at position 0 means shifting every other item by one slot — O(n). If you need a queue that takes items from the front, use collections.deque, which is O(1) at both ends.
sort() vs sorted()
list.sort() sorts the existing list and returns None. sorted(iterable) works on any iterable and returns a new list, leaving the original untouched. Both accept key= and reverse=True, and both are stable: items with equal keys keep their original order.
A real-life example
A batch job sends 100,000 queued prompts to an LLM, taking one at a time from the front of a list:
1from collections import deque23prompts = [f"Summarise ticket {i}" for i in range(100_000)]45queue = deque(prompts) # O(1) popleft6sent = 07while queue:8 prompt = queue.popleft() # with a list, prompts.pop(0) is O(n) each time9 sent += 110print(sent) # 100000With prompts.pop(0), each call shifts up to 99,999 items, so the whole loop does about 5 billion item moves and takes far longer than the network calls it feeds. deque.popleft() does it in constant time. The same job had a second bug: ranked = results.sort(key=...) left ranked as None, which crashed the report step. The fix was ranked = sorted(results, key=...).
Follow-up questions to expect
- "What is the difference between
remove,popanddel?" —remove(x)deletes by value;pop(i)deletes by index and returns the item;del lst[i]deletes by index or slice and returns nothing. - "Why is
pop(0)slow?" — Every remaining item shifts one slot left, so it is O(n). Usedeque.popleft(). - "Is
copy()a deep copy?" — No, it is shallow: nested lists inside are shared. Usecopy.deepcopyfor nested data.