How to slice a list of tuples in python?
Your solution looks like the most pythonic to me; you could also do
tuples = [(0,'a'), (1,'b'), (2,'c')]
print zip(*tuples)[0]
... but to me that's too "clever", and the list comprehension version is much clearer.
You can use *
unpacking with zip()
.
>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> for item in zip(*l)[0]:
... print item,
...
0 1 2
For Python 3, zip()
doesn't produce a list
automatically, so you would either have to send the zip
object to list()
or use next(iter())
or something:
>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> print(*next(iter(zip(*l))))
0 1 2
But yours is already perfectly fine.
You could convert it to a numpy array.
import numpy as np
L = [(0,'a'), (1,'b'), (2,'c')]
a = np.array(L)
a[:,0]