Search code examples
pythonpython-2.7list-comprehensionenumerate

Nested list comprehension with enumerate build-in function


I studying list comprehension and I stuck in the following code:

[[c for c in enumerate(r)] for r in enumerate(['a','b','c'])]

which returns:

[[(0, 0), (1, 'a')], [(0, 1), (1, 'b')], [(0, 2), (1, 'c')]]

However, I was expecting this:

[[(0,(0,'a'))],[(1,(1,'b'))],[(2,(2,'c'))]]

I read some articles but could not understand the prompted output. Someone can explain it to me, please.


Solution

  • You are enumerating each individual element of the outer enumerate():

    • You create one enumerate() over the list ['a', 'b', 'c'], this produces a sequence of tuples with (counter, letter).

    • You then apply enumerate() to each of the (counter, letter) tuples, producing (0, count) and (1, letter) tuples each.

    So in the end you get the following element for each of the letters in the list ['a', 'b', 'c']:

    [
        [(0, 0), (1, 'a')],  # enumerate((0, 'a'))
        [(0, 1), (1, 'b')],  # enumerate((1, 'b'))
        [(0, 2), (1, 'c')],  # enumerate((2, 'c'))
    ]
    

    If you wanted to get (counter, (counter, element)), you need to apply enumerate() to the whole output of enumerate(), not to each individual tuple:

    >>> [combo for combo in enumerate(enumerate(['a','b','c']))]
    [(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]
    

    You could just call list() on enumerate() too:

    >>> list(enumerate(enumerate(['a','b','c'])))
    [(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]