4

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]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
desiigner
  • 89
  • 1
  • 3
  • 10

2 Answers2

10

Use enumerate here

>>> l = ['A','A','B','A','B','B','A']
>>> [i for i,d in enumerate(l) if d=='B']
[2, 4, 5]
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
  • 1
    my humble request people who downvote answer should provide explanation so that we can improve. We are not expecting this eavesdropping with high reputation guys. – akash karothiya Oct 12 '17 at 05:32
  • I 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. – Anton vBR Oct 12 '17 at 08:30
  • @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. – akash karothiya Oct 12 '17 at 08:36
  • my bad, you are right, can't be undone anymore as time passed – Anton vBR Oct 12 '17 at 08:40
  • wait... I just apologized and you throw an attack back? Maybe you deserved that downvote anyhow. – Anton vBR Oct 12 '17 at 08:52
  • yah correcr @YvetteColomb that's the problem here :( – akash karothiya Oct 12 '17 at 09:28
  • I 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. – Bot_Start Jan 17 '21 at 23:57
6

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]
Alex Fung
  • 1,996
  • 13
  • 21
  • umm. Does this answer deserve downvotes? Can you elaborate why? – Alex Fung Oct 12 '17 at 05:29
  • Well, 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. – rustysys-dev Oct 12 '17 at 05:47
  • @Procyclinsur thanks for letting me know the potential confusion. Just fixed my answer. – Alex Fung Oct 12 '17 at 06:21