TryingLightning
TryingLightning

Reputation: 9

How to find the last occurrence of item in nested list?

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

Answers (1)

L3n95
L3n95

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.

  • The first loop iterates from last to first item [::-1] (You can also use .reverse() reverse)
  • and checks if the first item item[0] in the sublist is "colour". (Your [-1] checks the last item in the sublist, that are the numbers in your case)
  • If the first "colour" is found, the loop is breaked.

Upvotes: 5

Related Questions