Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice a list of lists

Tags:

python

slice

I have an input stream as follows:

data = [[1,234],[2,432],[3,443]]

How can I get the second element of every list? I can get the second value of a single entry by data[0][1], or every list in a range with both elements using data[0:2], but how to get just the second element from every list? Just looping through the list seems inefficient.

like image 990
PearsonArtPhoto Avatar asked Dec 10 '25 13:12

PearsonArtPhoto


2 Answers

Use a list comprehension:

[lst[1] for lst in data]
like image 73
Martijn Pieters Avatar answered Dec 12 '25 04:12

Martijn Pieters


Use operator and map:

from operator import itemgetter
map(itemgetter(1), data)
like image 26
Artsiom Rudzenka Avatar answered Dec 12 '25 06:12

Artsiom Rudzenka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!