3. Searching and Counting Methods in List
Python provides built-in ways to search for elements and count their occurrences in a list. These methods are helpful when working with data to check presence, locate position, or know frequency.
- Searching: To check whether an element is present in the list or not.
- Counting: To find how many times a particular element appears in the list.
Types of Searching and Counting Methods:
in / not in— Checks whether an element exists in the list or not.index()— Returns the index of the first occurrence of the element.count()— Returns how many times an element appears in the list.
1. in / not in
The in operator checks if a value exists in the list, while
not in checks if it does not exist.
Syntax:
element in list_name
element not in list_name
Example:
fruits = ['apple', 'banana', 'mango']
print('mango' in fruits)
print('kiwi' not in fruits)
Output:
True
True
Explanation:
- 'mango' is present in the list, so
inreturns True. - 'kiwi' is not in the list, so
not inreturns True.
2. index()
The index() method returns the position (index) of the first
occurrence of the given element.
If the element is not found, it raises a ValueError.
Syntax:
list_name.index(element)
Example:
numbers = [5, 10, 15, 20]
print(numbers.index(15))
Output:
2
Explanation:
- 15 is found at index 2 in the list.
- Indexing starts from 0, so 5 → 0, 10 → 1, 15 → 2, 20 → 3.
Example (When Element is Not Found):
names = ['Mudit', 'Shiva', 'Nishu']
print(names.index('Vansh'))
Output:
ValueError: 'Vansh' is not in list
Explanation:
- 'Vansh' is not present in the list
['Mudit', 'Shiva', 'Nishu']. - So, Python raises a
ValueErrorbecause it cannot find the element. - To avoid this error, we should first check using
inbefore callingindex().
3. count()
The count() method returns the number of times a specific element
appears in the list.
Syntax:
list_name.count(element)
Example:
colors = ['red', 'blue', 'green', 'blue', 'red', 'blue']
print(colors.count('blue'))
print(colors.count('yellow'))
Output:
3
0
Explanation:
- 'blue' appears 3 times in the list.
- 'yellow' does not appear at all, so count is 0.
Summary:
in→ Used to check if an element exists in the list.not in→ Used to check if an element does not exist in the list.index()→ Returns the index of the first occurrence of the element.count()→ Returns the number of times an element appears in the list.