Search code examples
pythonloopsenumerate

Enumerate and get the first item of each tuple?


How to get from this:

col = [('red', '132', '234'), ('green', '236', '434'), ('brown', '542', '457')]

to this:
EDIT (without any quotes)

1 red, 2 green, 3 brown   # enumerate and get the first item of each tuple.

I tried this, but it doesn't work:

[zip(((enumerate(col),1),i[0])) for i in col]

Only built-in functions please.


Solution

  • You can use list comprehension.

    >>> col = [('red', '132', '234'), ('green', '236', '434'), ('brown', '542', '457')]
    >>>
    >>> ["{} {}".format(index, first) for index, (first, *_) in enumerate(col, start=1)]
    ['1 red', '2 green', '3 brown']