in and count
- Python course
- Beginner
- Lesson 56/116
- 4 min
Learn membership with in and counting with count.
in and count
in checks whether an item is in the list. count counts how many of an item exist:
cart = ["Apple", "Bread", "Apple"]
print("Apple" in cart) # True
print(cart.count("Apple")) # 2in returns True/False; count returns a number. These methods are very handy for content searches.
Searching and counting
in and count are useful together: first check whether the item exists with in, then count how many with count:
cart = ["Apple", "Bread", "Apple", "Milk"]
if "Apple" in cart:
print("Has Apple:", cart.count("Apple"))This pattern is common in stock control and content search.
Practice Print in and count
Assign cart = ["Apple", "Bread", "Apple"]. Print print("Apple" in cart) and print(cart.count("Apple")).
Starter code
# in and countSample solution
cart = ["Apple", "Bread", "Apple"]
print("Apple" in cart)
print(cart.count("Apple"))Expected output
True 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does cart.count("Apple") return (cart has 2 Apples)?
- "Apple"
- True
- 2 Correct answer
- Error
Explanation: count counts how many of the item: 2.
2 Complete the in check
cart = ["Apple", "Bread"]
print("Apple" ____ cart)
cart = ["Apple", "Bread"]
print("Apple" in cart)
Explanation: in checks whether the item is in the list.
3 Match the search methods
| Term | Meaning |
|---|---|
in |
Presence check |
count |
Item count |
len |
Length |
index |
Item position |