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
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 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.
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 (, ).
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.
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
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