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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With