python
Find all indexes of an item in a list using python
To get all the occurrences of an item inside a list and get all the indexes, you can use the code examples described here.
#define the list
my_list = ['a', 'b', 'c', 'b', 'd', 'b', 'a']
#get all indexed of 'b'
indexes = [index for index, item in enumerate(my_list) if item == 'b']
print(indexes)
# -> [1, 3, 5]
We are perfoming following taks using above code snippet.
1. Created a python list variable named my_list that contains multiple items.
2. Passing my_list variable to enumerate() function and creating for loop using this.
3. Checking inside the loop if the item is equal to 'b' and returning index if condition satisfied.
4. Printing indexes list. If the item does not exist in the list, it will print a blank array.
Was this helpful?
Similar Posts
- Find the most repeated item from a list in Python
- Remove an item from python list using its index
- Check if item exists in a list using python
- Find the smallest number in a python list
- Find the largest number in a list Python
- Find minimum value from a List in Python
- Python - regex , remove all single characters,replace all single chars,char