Python List Methods
list_name.append(item)
list_name.insert(index, item)
list_name.remove(item)
list_name.pop(index)
Adding Items
append() adds a single item to the end in O(1) time, insert(i, x) places an item at a specific position (shifting everything after it), and extend() merges another iterable's items in one at a time -- extend(other_list) is very different from append(other_list), which would nest the whole list as one element.
Example: Adding Items
items = [1, 2]
items.append(3) # adds 3 to the end
items.insert(0, 0) # inserts 0 at position 0, shifting the rest right
items.extend([4, 5]) # adds each item of the list individually
print(items)
Removing Items
remove(value) deletes the first matching value and raises ValueError if it isn't found, pop(index) removes and returns the item at that position (defaulting to the last item), and clear() empties the list entirely -- pop() is the only one of the three that hands you back what was removed.
Example: Removing Items
items = [1, 2, 3, 2]
items.remove(2) # removes only the first matching 2
last = items.pop() # removes and returns the last item
print(items, last)
Finding Items
index(value) returns the position of the first occurrence of a value (raising ValueError if absent), while count(value) tells you how many times it appears -- useful together when you need to confirm an item exists before searching for its exact location.
Example: Finding Items
items = [1, 2, 3, 2]
print(items.index(2)) # position of the first 2
print(items.count(2)) # how many times 2 appears
Sorting and Reversing
sort() rearranges the list in place using each element's natural ordering (or a custom key function) and returns None, which is why 'my_list = my_list.sort()' is a classic bug; reverse() simply flips the current order without any comparison logic.
Example: Sorting and Reversing
items = [3, 1, 2]
items.sort() # sorts in place, returns None
print(items)
items.reverse() # flips the current order
print(items)
Copying Lists
Writing new_list = old_list only copies the reference, so changes through either name affect the same underlying list -- copy() (or the slice trick list[:]) creates a genuinely separate list, though nested lists inside it are still shared (a shallow copy).
Example: Copying Lists
original = [1, 2, 3]
copy = original.copy() # creates a separate list, not just another reference
copy.append(4)
print(original, copy) # original is unaffected
- Assigning the result of
sort()orappend(), as innums = nums.sort(), which setsnumstoNonebecause these methods change the list in place. - Using
remove(x)on a value that is not in the list, which raisesValueError; check withif x in itemsfirst. - Using
append()when you want to add several items, soa.append([4, 5])nests a list instead ofa.extend([4, 5]).
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: