Get the nth item from an internal list of a list of lists in Python

Possible duplicate:
Effective use of the first elements in the internal list

Let's say I have:

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

I want to get the first element of each of the internal lists:

 b = [1,2,3] 

Without having to do this (my current hack):

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

I am sure that there is one liner for him, but I really do not know what I'm looking for.

+6
source share
1 answer

Just change your list:

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

Or:

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

Or, if you are dealing with "right 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] 
+25
source

All Articles