How to find all the indexes of a recurring item in a list?
13,314
Solution 1
Use enumerate
here
>>> l = ['A','A','B','A','B','B','A']
>>> [i for i,d in enumerate(l) if d=='B']
[2, 4, 5]
Solution 2
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]
Comments
-
desiigner almost 2 years
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]
-
Anton vBR over 6 yearsDid you Google this first? -1
-
Pradip Das over 6 years
-
-
Alex Fung over 6 yearsumm. Does this answer deserve downvotes? Can you elaborate why?
-
akash karothiya over 6 yearsmy humble request people who downvote answer should provide explanation so that we can improve. We are not expecting this eavesdropping with high reputation guys.
-
rustysys-dev over 6 yearsWell, I didn't downvote you.. but you didn't explain your answer well.. at first glance, I would argue that you said not to use the default data structure list, dict as a variable but then you used 'a list' to create a variable... which if not properly worded might be confused by someone who doesn't know what they are doing... and think you have contradicted yourself... I see what you mean't so I will fix you an even 0, but you should clarify more.
-
Alex Fung over 6 years@Procyclinsur thanks for letting me know the potential confusion. Just fixed my answer.
-
Anton vBR over 6 yearsI downvoted because I thought this was a mere copy of another answer. Questions like these should be deleted altogether for the simple fact OP didnt even make a minimal effort to find the answer.
-
akash karothiya over 6 years@AntonvBR that doesn't mean you downvote the working answer. You can report it as duplicate or atleast raise a flag. Downvoting working answer is not acceptable.
-
Anton vBR over 6 yearsmy bad, you are right, can't be undone anymore as time passed
-
Anton vBR over 6 yearswait... I just apologized and you throw an attack back? Maybe you deserved that downvote anyhow.
-
akash karothiya over 6 yearsyah correcr @YvetteColomb that's the problem here :(
-
Bot_Start over 3 yearsI did know ppl fight over here too. But the answers deserve an upvote and the OP did not even bother to mark it as the correct answer. What a shame.