Python: how can I get rid of the second element of each sublist?

I have a list of subscriptions, for example:

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

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

[501, 501, 501, 501]

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

+3
source share
3 answers
a = [[501, 4], [501, 4], [501, 4], [501, 4]]
b = [c[0] for c in a]
+2
source

You can use 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]
+7
source

Less puffonic, functional version using map:

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

Less pythonic since it doesn't use lists. See here .

+1
source

Source: https://habr.com/ru/post/1768794/


All Articles