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

Viewed 192

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?

4 Answers

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.

Using list comprehension and getting the first element from each tuple:

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

print([i[0] for i in c])

OUTPUT:

[1, 2]  

Another way doing this is:

[x[0] for x in c]

Use the zip() function.

b = [*list(zip(*a))[0]]
Related