Search code examples
pythonlistindices

How to add indices to a list?


For example, I have a list = ['a', 'b', 'c'].
What I want is a list indexed(list) == [(1, 'a'), (2, 'b'), (3, 'c)].

Is there a builtin or module for this?


Solution

  • You can use the built-in function enumerate to achieve that.

    In [1]: a = ['a', 'b', 'c']
    
    In [2]: b = [(idx, item) for idx,item in enumerate(a)]
    
    In [3]: b
    Out[3]: [(0, 'a'), (1, 'b'), (2, 'c')]
    

    Note: the default indice would start with 0, but you could try to add start=1 to config that, e.g.

    In [4]: c = [(idx, item) for idx,item in enumerate(a, start=1)]
    
    In [5]: c
    Out[5]: [(1, 'a'), (2, 'b'), (3, 'c')]
    

    Hope it helps.