Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
Andre Avatar asked Nov 20 '15 14:11

Andre


People also ask

Can you slice tuples in Python?

Slicing. We can access a range of items in a tuple by using the slicing operator colon : . Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.

Can you slice a list Python?

It's possible to "slice" a list in Python. This will return a specific segment of a given list. For example, the command myList[2] will return the 3rd item in your list (remember that Python begins counting with the number 0).

How do I slice a data list in Python?

The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.

Can a tuple be sliced the same way as a list?

Slices for strings and tuples So far, we have shown examples of lists ( list type), but slices can be used with other sequence objects such as strings str and tuples tuple as well. However, str and tuple are immutable, so new values cannot be assigned.


1 Answers

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.

like image 88
TigerhawkT3 Avatar answered Oct 12 '22 23:10

TigerhawkT3