Lists have built-in methods to modify them directly.
Adding items
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']
Extend with multiple items:
more = ["grape", "kiwi"]
fruits.extend(more)
print(fruits) # Adds grape and kiwi
Removing items
fruits.remove("banana") # Removes first "banana"
print(fruits)
popped = fruits.pop() # Removes and returns last item
print(popped) # kiwi
fruits.pop(0) # Removes item at index 0
Clear all:
fruits.clear()
print(fruits) # []
Sorting and reversing
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5]
numbers.reverse()
print(numbers) # [5, 4, 3, 1, 1]
Counting and indexing
numbers = [1, 2, 2, 3]
print(numbers.count(2)) # 2
print(numbers.index(3)) # 3 (first position)
Simple examples
Shopping list:
shopping = ["milk", "bread"]
shopping.append("eggs")
shopping.remove("bread")
print(shopping) # ['milk', 'eggs']
Sort names:
names = ["bob", "alice", "charlie"]
names.sort()
print(names) # ['alice', 'bob', 'charlie']
Quick summary
- Add with
.append(),.insert(),.extend(). - Remove with
.remove(),.pop(),.clear(). - Sort with
.sort(), reverse with.reverse(). - Check with
.count(),.index().
Practice list methods on collections. They make working with lists efficient in Python programs.
Top comments (1)
Python lists come with built-in tools to change, organize, and inspect data without extra effort.
To add items, use append() for single values, insert() for a specific position, and extend() to merge another list.
To remove items, remove() deletes the first match, pop() removes by index (or last item if empty), and clear() wipes the whole list.
For ordering, sort() changes the list directly, while reverse() flips it in place.
You can also inspect data with count() to see occurrences and index() to find the first position of a value.
Most of the time, you combine these methods to quickly shape lists into whatever structure your program needs.