I want to take the indices of each element in the list a=[2,4,5,2]
when I enter  a.index(2) I get 0 as output. How can I take the index of the fourth element like that way in Python?
            Asked
            
        
        
            Active
            
        
            Viewed 89 times
        
    2
            
            
         
    
    
        Taku
        
- 31,927
- 11
- 74
- 85
 
    
    
        Sarith Wasitha
        
- 29
- 2
- 
                    2`a.index(2)` returns the index of the first `2` in `a`. Did you mean you want to access the element `4` (different from the fourth element)? That would simply be `a[1]` (python indexing starts at 0). Also try `[(i, x) in enumerate(a)]`. – pault Jan 27 '18 at 06:11
- 
                    Well, there are 2 twos, so it gets the first one – whackamadoodle3000 Jan 27 '18 at 06:11
- 
                    2`index()` only gets the index of the first occurrence. Do you want all the indexes for each item? – RoadRunner Jan 27 '18 at 06:11
3 Answers
2
            
            
        You could recover all the indices like so
indices = [i for i in xrange(len(a)) if a[i] == 2]
 
    
    
        Olivier Melançon
        
- 21,584
- 4
- 41
- 73
1
            
            
        You could try this to get them all:
[print i for i,v in enumerate(a) if v==2] # or any number
 
    
    
        whackamadoodle3000
        
- 6,684
- 4
- 27
- 44
- 
                    
- 
                    Good point. I will change it. However, in Python 2, using parenthesis still works. It just simplifies it like an expression – whackamadoodle3000 Jan 27 '18 at 06:22
1
            
            
        You could also store the indexes for each item in a collections.defaultdict():
from collections import defaultdict
a=[2,4,5,2]
indexes = defaultdict(list)
for i, e in enumerate(a):
    indexes[e].append(i)
print(indexes)
Which gives:
defaultdict(<class 'list'>, {2: [0, 3], 4: [1], 5: [2]})
Then you could access the indexes for each item like this:
>>> indexes[2]
[0, 3]
>>> for i in indexes[2]:
...     print(i, '-->', a[i])
... 
0 --> 2
3 --> 2
Or as @Idlehands pointed out in the comments, you can use dict.setdefault() here:
indexes = {}
for i, e in enumerate(a):
    indexes.setdefault(e, []).append(i)
print(indexes)
Which also gives:
{2: [0, 3], 4: [1], 5: [2]}
 
    
    
        RoadRunner
        
- 25,803
- 6
- 42
- 75
- 
                    You can also do this with the `built-in dict`. `indexes.setdefault(e, list()).append(i)` would work just the same. – r.ook Jan 27 '18 at 06:39
- 
                    @Idlehands Yep that would work just as great. Even more efficient: `indexes.setdefault(e, []).append(i)`. I believe using `[]` is less costly than `list()`, I could be mistaken though. – RoadRunner Jan 27 '18 at 06:53