Skip to main content
2 of 3
Used a more direct cross reference (as user names can change at any time).
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

A variant on the answers from FMc and user7177 will give a dict that can return all indices for any entry:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much'] >>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a)))) >>> l['foo'] [0, 5] >>> l ['much'] [6] >>> l {'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]} 

You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

bvanlew
  • 1.5k
  • 16
  • 14