Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
List Methods & Operations
Python lists have powerful built-in methods for adding, removing, searching, and manipulating elements.
List Methods
fruits = ["apple", "banana", "cherry", "banana"]
# Adding
fruits.append("date") # add to end
fruits.insert(0, "avocado") # insert at position
fruits.extend(["fig", "grape"]) # add multiple
# Removing
fruits.remove("banana") # remove first occurrence
popped = fruits.pop() # remove & return last
popped_at = fruits.pop(0) # remove & return at index
# del fruits[0] # delete at index
# Searching
print(fruits.index("cherry")) # find index
print(fruits.count("banana")) # count occurrences
# Sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # sort in place
print(numbers)
numbers.sort(reverse=True) # sort descending
print(numbers)
# Copy (avoid aliasing bugs!)
original = [1, 2, 3]
copy1 = original.copy() # shallow copy
copy2 = original[:] # slice copy
copy3 = list(original) # constructor copy
# Joining lists
a = [1, 2]
b = [3, 4]
c = a + b # [1, 2, 3, 4]
d = a * 3 # [1, 2, 1, 2, 1, 2]
print(c, d)Tip
Tip
Use list.copy() or list[:] to avoid aliasing bugs. a = b makes both point to the SAME list - changes to one affect the other.
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
list.sort() modifies in place and returns None. sorted(list) returns a new sorted list. Don't do x = mylist.sort() - x will be None.
Practice Task
Note
(1) Sort a list ascending and descending. (2) Remove duplicates using set(). (3) Demonstrate the aliasing bug and fix it with .copy().