How to get every n-th element from a multi-dimensional Python list?

Question:

From

lst = [ ['a', 1], ['b', 2] ]

How can I get a new list [1, 2] from it?

lst[0:2][1] works iteratively, so it doesn’t work.

Is that possible without any loops?

Asked By: just in

||

Answers:

you can use list comprehension

lst = [ ['a', 1], ['b', 2] ]
n=1

result=[i[n] for i in lst ]

#=>[1, 2]
Answered By: Ran A

Using map:

>>> from operator import itemgetter
>>> list(map(itemgetter(1), lst))
[1, 2]
Answered By: Mechanic Pig
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.