How can I find all the indexes of a recurring item? For Example:
list = ['A', 'A', 'B', 'A', 'B', 'B', 'A']
I want to return all occurrences of 'B', so it'd return:
indexes = [2, 4, 5]
How can I find all the indexes of a recurring item? For Example:
list = ['A', 'A', 'B', 'A', 'B', 'B', 'A']
I want to return all occurrences of 'B', so it'd return:
indexes = [2, 4, 5]
Use enumerate
here
>>> l = ['A','A','B','A','B','B','A']
>>> [i for i,d in enumerate(l) if d=='B']
[2, 4, 5]
NEVER EVER use default data structure e.g. list
, dict
as variables.
This should do it:
from collections import defaultdict
# Create a dict with empty list as default value.
d = defaultdict(list)
# Initialise the list.
l = ['A','A','B','A','B','B','A']
# Iterate list with enumerate.
for index, e in enumerate(l):
d[e].append(index)
# Print out the occurrence of 'B'.
print(d['B'])
Output:
[2, 4, 5]