Home > Net >  Getting every n-th element from multi-dimensional Python list
Getting every n-th element from multi-dimensional Python list

Time:09-08

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?

CodePudding user response:

you can use list comprehension

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

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

#=>[1, 2]

CodePudding user response:

Using map:

>>> from operator import itemgetter
>>> list(map(itemgetter(1), lst))
[1, 2]

CodePudding user response:

I don't think it's possible to get something from a list without traversing through it.

  • Related