27

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.

Community
  • 1
  • 1
jsj
  • 9,019
  • 17
  • 58
  • 103

1 Answers1

72

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]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280