tags:

views:

58

answers:

3

I have a list of sublists, such as:

[[501, 4], [501, 4], [501, 4], [501, 4]]

How can I get rid of the second element for each sublist ? (i.e. 4)

[501, 501, 501, 501]

Should I iterate the list or is there a faster way ? thanks

+6  A: 

You can use a list comprehension to take the first element of each sublist:

xs = [[501, 4], [501, 4], [501, 4], [501, 4]]
[x[0] for x in xs]
# [501, 501, 501, 501]
sepp2k
+2  A: 
a = [[501, 4], [501, 4], [501, 4], [501, 4]]
b = [c[0] for c in a]
ars
+1  A: 

A less pythonic, functional version using map:

a = [[501, 4], [501, 4], [501, 4], [501, 4]]
map(lambda x: x[0], a)

Less pythonic, since it does not use list comprehensions. See here.

cschol
@cschol: I deleted my comment because wikipedia disagreed with me about what the first language with list comprehensions was, but you misunderstood me: My point was that using list comprehensions is just as functional as using `map` and `filter`.
sepp2k
@sepp2k I deleted mine too. And I agree with you. I intended this to be a nice complementary answer for people.
cschol