Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference an Element in a List of Tuples

Tags:

Sorry in advance, but I'm new to Python. I have a list of tuples, and I was wondering how I can reference, say, the first element of each tuple within the list. I would think it's something like

for i in number_of_tuples :   first_element = myList[i[0]] 

you know, [list_element[tuple_element]]? However, this doesn't appear to be the right approach. Any help would be greatly appreciated.

Thanks,

Turner

like image 624
Turner Hughes Avatar asked Jun 23 '11 13:06

Turner Hughes


People also ask

How do you access elements in 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.

How do you index a tuple inside a list?

Use a list comprehension to iterate over the list of tuples. On each iteration, return the tuple item you want to check for. Use the list. index() method to get the index of the first tuple with the specified value.

How do you get a tuple from a list?

Typecasting to tuple can be done by simply using tuple(list_name). Approach #2 : A small variation to the above approach is to use a loop inside tuple() . This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma (, ).

Does Index () work on tuples?

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function basically performs two functions: Giving the first occurrence of an element in the tuple. Raising an exception if the element mentioned is not found in the tuple.


1 Answers

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

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.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]  info[0][0] == 1 info[0][1] == 2 info[1][0] == 3 info[1][1] == 4 info[2][0] == 5 info[2][1] == 6 
like image 132
Prodigal Maestro Avatar answered Sep 26 '22 18:09

Prodigal Maestro