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]
Share:
13,314
desiigner
Author by

desiigner

Just trying to pass

Updated on July 16, 2022

Comments

  • desiigner
    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]
    
  • Alex Fung
    Alex Fung over 6 years
    umm. Does this answer deserve downvotes? Can you elaborate why?
  • akash karothiya
    akash karothiya over 6 years
    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.
  • rustysys-dev
    rustysys-dev over 6 years
    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.
  • Alex Fung
    Alex Fung over 6 years
    @Procyclinsur thanks for letting me know the potential confusion. Just fixed my answer.
  • Anton vBR
    Anton vBR over 6 years
    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.
  • akash karothiya
    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
    Anton vBR over 6 years
    my bad, you are right, can't be undone anymore as time passed
  • Anton vBR
    Anton vBR over 6 years
    wait... I just apologized and you throw an attack back? Maybe you deserved that downvote anyhow.
  • akash karothiya
    akash karothiya over 6 years
    yah correcr @YvetteColomb that's the problem here :(
  • Bot_Start
    Bot_Start over 3 years
    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.