suppose we have:
a = [[1, 2, 3], [4, 5, 6]]
What is the fastest way to access the array such that we get the first element in each list, other than looping.
i would like the result to be giving me... 1,4
using zip(*a)
a = [[1, 2, 3], [2, 3, 4]]
result = zip(*a)[0]
print result
zip
returns an iterable object... next(iter(zip(*a)))
should work just about anywhere though.list(zip(*a))[0]
works in python2.7, and IMHO will also work in python3.0, because list()
accepts an iterable and produces a list.Without looping, you need to unroll the loop as ethg242 does. This has the disadvantage of only working for a fixed length of a
Here is a list comprehension
[i[0] for i in a]
It's also possible to use map()
, but this also has an implicit loop
from operator import itemgetter
map(itemgetter(0), a)
You might want to consider numpy:
>>> import numpy as np
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = np.array(a)
>>> b[:,0]
array([1, 4])