Separate list by entries
Question: I have a Python list that I know contains the entries `1`, `2`, and `7`, e.g.,

    
    
    data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
    

I would now like to get all of the indices of each entry, i.e.,

    
    
    g1 = [0, 3, 4, 5, 9]
    g2 = [2, 6, 7, 12]
    g7 = [1, 8, 10, 11]
    

The `data` array can be long, so efficiency matters. How do I achieve this?


Answer: You could use a
[`defaultdict`](https://docs.python.org/3/library/collections.html#defaultdict-
examples) in order to collect indices of elements per group:

    
    
    In [1]: from collections import defaultdict
    
    In [2]: data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
    
    In [3]: indices = defaultdict(list)
    
    In [4]: for i, d in enumerate(data):
       ...:     indices[d].append(i)
       ...:     
    
    In [5]: indices
    Out[5]: defaultdict(<class 'list'>, {1: [0, 3, 4, 5, 9], 2: [2, 6, 7, 12], 7: [1, 8, 10, 11]})
    

