Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - get list of tuples first index?

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] 
like image 905
user1413824 Avatar asked May 24 '12 10:05

user1413824


People also ask

How do you get the first index of a tuple in Python?

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.

How do you find the first element in a list tuple?

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.

How do you access a list of tuples?

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.


1 Answers

use zip if you need both

>>> r=(1,'one'),(2,'two'),(3,'three') >>> zip(*r) [(1, 2, 3), ('one', 'two', 'three')] 
like image 151
gsagrawal Avatar answered Sep 21 '22 08:09

gsagrawal