Python List Methods
Python list methods count, find, add, and remove items in a list.
Count a value with count()
count() gives 0 when the value is not there.
rolls = [6, 2, 6, 4, 6, 1]
print(rolls.count(6))
print(rolls.count(3))Find a position with index()
index() gives the first match only.
rolls = [6, 2, 6, 4]
print(rolls.index(2))
print(rolls.index(6))Add and remove in one place
insert() and remove() are from the earlier list lessons.
fruits = ["apple", "banana"]
fruits.insert(1, "kiwi")
print(fruits)
fruits.remove("banana")
print(fruits)Use a list as a stack
The last item you add is the first item you take back.
stack = []
stack.append("first")
stack.append("second")
print(stack.pop())
print(stack)Example
rolls = [4, 6, 2, 6, 3, 6, 5]
print(rolls.count(6))
print(rolls.index(6))
print(rolls.index(3))Key points
- Use count() to count how many times a value appears
- Use index() to find the first position of a value
- Use append() and extend() to add items, and insert() to add at a position
- Use remove() and pop() to take items out, and clear() to empty a list
- Stack: a list used last in, first out, with append() to push and pop() to take
- List methods act on a list to count, find, add, or remove items.
- Check with in first if you are not sure.
In this example, rolls holds seven dice rolls. count(6) counts the sixes and gives 3. index(6) finds the first six at position 1. index(3) finds the three at position 4. Each print shows one of those three answers.
Note
index() raises ValueError when the value is not in the list.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does [5, 5, 2].index(2) give?