Shapi
Shapi

Reputation: 5593

How to slice a list of tuples in python?

Assuming:

L = [(0,'a'), (1,'b'), (2,'c')]

How to get the index 0 of each tuple as the pretended result:

[0, 1, 2]

To get that I used python list comprehension and solved the problem:

[num[0] for num in L]

Still, it must be a pythonic way to slice it like L[:1], but of course this slincing dont work.

Is there better solution?

Upvotes: 22

Views: 23881

Answers (5)

etotheipi
etotheipi

Reputation: 871

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]

Upvotes: 2

Emile
Emile

Reputation: 2971

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.

Upvotes: 2

Mr. E
Mr. E

Reputation: 2120

What about map?

map(lambda (number, letter): number, L)

To slice it in python 2

map(lambda (number, letter): number, L)[x:y]

In python 3 you must convert it to list first:

list(map(lambda (number, letter): number, L))[x:y]

Upvotes: 0

Mayur Koshti
Mayur Koshti

Reputation: 1852

>>> list = [(0,'a'), (1,'b'), (2,'c')]
>>> l = []
>>> for t in list:
        l.append(t[0])

Upvotes: -1

TigerhawkT3
TigerhawkT3

Reputation: 49318

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.

Upvotes: 9

Related Questions