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 (0)