What's the most compact way to return the following:
Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements.
For:
[(1,'one'),(2,'two'),(3,'three')]
returned list would be
[1,2,3]
Use indexing to get the first element of each tuple Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.
We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list.
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
use zip if you need both
>>> r=(1,'one'),(2,'two'),(3,'three') >>> zip(*r) [(1, 2, 3), ('one', 'two', 'three')]
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