Search code examples
pythonpython-3.xcoding-style

How to convert a list of 2-tuples to a list of their first elements


I have a list like this-

[(1, 3),(2, 2)]

I like to convert it to-

[1,2]

What I am doing is-

c = [(1, 3),(2, 2)]
output = []
for a,b in c:
    output.append(a)
return output

Is there any way for doing this in 1 line?


Solution

  • You can use a list-comprehension

    output = [a for a,_ in c]
    

    Here the _, corresponding to the b used in the question, is the conventional name given to a dummy variable.