Reputation: 9
I have a randomly generated list with a similar format
data = [['item','A'],['colour',1],['colour',3],['item','D']]
I want to find where 'colour' last occurred and print the number associated with it
for item in data:
if item[-1] == 'colour':
print(item[1])
this loop I have now prints nothing
Upvotes: 0
Views: 141
Reputation: 1615
You can change it to:
for item in data[::-1]:
if item[0] == 'colour':
print(item[1])
break
You have to change three things.
[::-1]
(You can also use .reverse()
reverse)item[0]
in the sublist is "colour"
. (Your [-1]
checks the last item in the sublist, that are the numbers in your case)"colour"
is found, the loop is break
ed.Upvotes: 5