-4

I know this is super basic but it's giving me problems. I have a tuple that I want to return a specific value from.

Code:

mytuple=[('A', 'B', 'C', 'D', 'E', 'F','G'),('H', 'I', 'J', 'K', 'L', 'M','N')]
print mytuple[0:1]

Desired Output:

B
user2242044
  • 8,803
  • 25
  • 97
  • 164

3 Answers3

2

The object that you've named mytuple is not, in fact, a tuple. It is a list containing two tuples. That's probably what's confusing you.

To get the first of the two tuples you would do:

 my_real_tuple = my_tuple_list[0]

and then to get the second element of the tuple:

print my_real_tuple[1]

These can be simplified into

print my_tuple_list[0][1]
Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
1

Here is what you are looking for, you need to specify the index of the list + the index of the tuple.

print mytuple[0][1]
Oscar
  • 231
  • 4
  • 17
0

You need to do two separate indexes:

print mytuple[0][1]

mytuple[0] will return the first tuple in mytuple:

>>> mytuple[0]
('A', 'B', 'C', 'D', 'E', 'F', 'G')
>>>

We then index that with [1] to return the item at index 1:

>>> mytuple[0][1]
'B'
>>>

Your current code is no different than:

print mytuple[:1]

which slices the list mytuple and gets everything before index 1 (which is just the first tuple):

>>> mytuple[:1]
[('A', 'B', 'C', 'D', 'E', 'F', 'G')]
>>>