Reputation: 1743
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
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
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
Reputation: 6958
How about:
>>> map(lambda e: e[0], (e for e in a))
[1, 4, 100, 4]
Upvotes: 1
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
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