Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the indexes of a recurring item in a list? [duplicate]

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]
like image 747
desiigner Avatar asked Sep 20 '25 08:09

desiigner


2 Answers

Use enumerate here

>>> l = ['A','A','B','A','B','B','A']
>>> [i for i,d in enumerate(l) if d=='B']
[2, 4, 5]
like image 59
akash karothiya Avatar answered Sep 22 '25 23:09

akash karothiya


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]
like image 45
Alex Fung Avatar answered Sep 22 '25 22:09

Alex Fung