Reputation: 173
I have a list :lst=[(1, 'AAT'), (2, 'C'), (33, 'GCC'), (4, 'T'), (11, 'ATC'), (12, 'A')]
I want to create a function, if I give it a number it search in the list lst
then it gives me the corresponding string .
for example : func(2) gives C
.
I try this:
def func(number):
for i in range(len(lst)):
if number==lst[i][0]: """ lst[1][0]==2"""
return lst[i][i]
it gives:
IndexError: tuple index out of range
what can I do?
Upvotes: 0
Views: 55
Reputation: 1122282
You are returning index i
of the tuple, which has only indices 0
and 1
. Return index 1 instead:
return lst[i][1]
or, use next()
and a generator expression:
def func(number):
return next(t[1] for t in lst if t[0] == number)
Upvotes: 1
Reputation: 34146
I think you wanted to return
lst[i][1]
instead of
lst[i][i]
The tuples inside the list are just of length 2
, so when your i
index is >
than 1
, it will throw an error.
Upvotes: 3