Reference an Element in a List of Tuples Reference an Element in a List of Tuples python python

Reference an Element in a List of Tuples


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] == 1info[0][1] == 2info[1][0] == 3info[1][1] == 4info[2][0] == 5info[2][1] == 6


You can get a list of the first element in each tuple using a list comprehension:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']>>> first_elts = [x[0] for x in my_tuples]>>> first_elts[1, 'a', True, 'q']


The code

my_list = [(1, 2), (3, 4), (5, 6)]for t in my_list:    print t

prints

(1, 2)(3, 4)(5, 6)

The loop iterates over my_list, and assigns the elements of my_list to t one after the other. The elements of my_list happen to be tuples, so t will always be a tuple. To access the first element of the tuple t, use t[0]:

for t in my_list:    print t[0]

To access the first element of the tuple at the given index i in the list, you can use

print my_list[i][0]