Get the nth element from the inner list of a list of lists in Python

45,445

Simply change your list comp to be:

b = [el[0] for el in a]

Or:

from operator import itemgetter
b = map(itemgetter(0), a)

Or, if you're dealing with "proper arrays":

import numpy as np
a = [ [1,2], [2,9], [3,7] ]
na = np.array(a)
print na[:,0]
# array([1, 2, 3])

And zip:

print zip(*a)[0]
Share:
45,445

Related videos on Youtube

jsj
Author by

jsj

Updated on August 05, 2022

Comments

  • jsj
    jsj over 1 year

    Possible Duplicate:
    First items in inner list efficiently as possible

    Lets say I have:

    a = [ [1,2], [2,9], [3,7] ]
    

    I want to retrieve the first element of each of the inner lists:

    b = [1,2,3]
    

    Without having to do this (my current hack):

    for inner in a:
        b.append(inner[0])
    

    I'm sure there's a one liner for it but I don't really know what i'm looking for.

  • Ashwini Chaudhary
    Ashwini Chaudhary over 11 years
    I guess there's no other alternative left to achieve this. :)
  • Jon Clements
    Jon Clements over 11 years
    @AshwiniChaudhary I'm struggling as to what else I can think of... gimme a bit ;) - do you reckon map(next, map(iter, a)) is pushing it?
  • Ashwini Chaudhary
    Ashwini Chaudhary over 11 years
    it's nice, but slow compared to the others.
  • Dannid
    Dannid about 6 years
    I like that zip(*a)[0] suggestion!
  • kevin_theinfinityfund
    kevin_theinfinityfund almost 4 years
    In Python 3, zip() returns an iterator, not a list, so you need list(zip(*a))[0], which ironically returns a tuple, so you need another list() wrapped around it if you need a list returned.