Python Data Structures
Python List Methods
Python lists come with built-in methods for adding, removing, searching, and reordering items — no external library needed.
Adding Items
append() adds one item to the end of a list. insert() places an item at a specific index, shifting the rest to the right. extend() adds every item from another iterable, one by one.
nums = [1, 2, 3]
nums.append(4) # [1, 2, 3, 4]
nums.insert(0, 0) # [0, 1, 2, 3, 4]
nums.extend([5, 6]) # [0, 1, 2, 3, 4, 5, 6]
print(nums)Removing Items
remove() deletes the first matching value. pop() removes and returns an item by index (defaults to the last item) — useful when you need the removed value, for example when building a stack.
nums = [0, 1, 2, 3]
nums.remove(1) # removes value 1 -> [0, 2, 3]
last = nums.pop() # removes and returns 3
first = nums.pop(0) # removes and returns 0
print(nums, last, first)Sorting and Reversing
sort() reorders a list in place (ascending by default; pass reverse=True for descending). reverse() simply flips the current order. Both change the original list rather than returning a new one.
scores = [88, 45, 92, 60]
scores.sort() # [45, 60, 88, 92]
scores.sort(reverse=True) # [92, 88, 60, 45]
scores.reverse() # flips current order
print(scores)Searching and Counting
count() tells you how many times a value appears, and index() finds the position of the first match — both are handy when validating user input or analysing data inside functions.
letters = ["a", "b", "a", "c", "a"]
print(letters.count("a")) # 3
print(letters.index("c")) # 3Quick-Reference Table
| Method | What it does | Example |
|---|---|---|
| append(x) | Add x to the end | nums.append(5) |
| insert(i, x) | Insert x at index i | nums.insert(0, 5) |
| remove(x) | Remove first item equal to x | nums.remove(5) |
| pop(i) | Remove and return item at i (default last) | nums.pop() |
| sort() | Sort the list in place | nums.sort() |
| reverse() | Reverse the list in place | nums.reverse() |
| count(x) | Count occurrences of x | nums.count(2) |
| index(x) | Index of first occurrence of x | nums.index(2) |
| extend(iter) | Append all items from iter | nums.extend([6, 7]) |
sort() and reverse() return None — do not write nums = nums.sort(), or you will lose your list and get None instead.
