How do I index numbers from a tuple in a list? For example, in the list [((8, 2), 0), ((3, 4), 2), ((1, 9), 2)], if I wanted to index the number 0, how would I do that while iterating though the list in a for loop?
We’d need to see this in some context, but what you’ve got is a list of
2-tuples, and each 2-tuple contains a 2-tuple and an int. And you want
the int.
Untested example:
for item in your_list:
inner_tuple = item[0]
the_int = item[1]
print("inner tuple", inner_tuple)
print("the int", the_int)
Depending what you need to do that are a few different ways of writing
this.
Suppose we have mylist = [((8, 2), 0), ((3, 4), 2), ((1, 9), 2)]
. The result for mylist[0]
is ((8, 2), 0)
. That’s still a tuple, so you need to index into it as well: mylist[0][1]
will give 0
.
for
loops can be explained similarly. One loop will loop over the top-level items, and you can nest loops to loop over inner items in each tuple.
for x in mylist:
for y in x:
print(y)
will print out each item of each tuple in the list.
With this information, you can use multiple indexes or multiple for loops to work with your nested data.