Alexander
Alexander

Reputation: 1743

Given a list of Tuples, return a new list of the first values of the tuples

I have a list of tuples and I want a new list consisting of the first values of the tuples.

I.e. if the list is:

[(1,5),(4,10),(100,3),(4,8)]

I want to create the following list:

[1,4,100,4]

The following code works:

a = [(1,5),(4,10),(100,3),(4,8)]
l = []
for i in range(len(a)):
    l.append(a[i][0])

But it seems there should be a better way, for example:

l = itertools.chain(for i in range(len(a)) a[i][0]) #This won't work

Upvotes: 3

Views: 121

Answers (5)

hochl
hochl

Reputation: 12930

How about a list comprehension:

l=[(1,5),(4,10),(100,3),(4,8)]
print [x[0] for x in l]

This will give you

[1, 4, 100, 4]

as requested :)

Upvotes: 7

Akavall
Akavall

Reputation: 86178

If you don't want to do list comprehension, you could try this:

x = [(1,5),(4,10),(100,3),(4,8)]

first_vals = list(zip(*x)[0])

Result:

>>> first_vals
[1, 4, 100, 4]

Upvotes: 3

Brian Gesiak
Brian Gesiak

Reputation: 6958

How about:

>>> map(lambda e: e[0], (e for e in a))
[1, 4, 100, 4]

Upvotes: 1

Nolen Royalty
Nolen Royalty

Reputation: 18633

Try this:

>>> a = [(1,5),(4,10),(100,3),(4,8)]
>>> [b[0] for b in a]
[1, 4, 100, 4]

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 601539

I'd usually use a list comprehension:

>>> a = [(1,5),(4,10),(100,3),(4,8)]
>>> [x for x, y in a]
[1, 4, 100, 4]

Upvotes: 8

Related Questions