Reputation: 383
I've a numeric list containing several repeated items like such:
list1 = [40, 62, 0, 5, 8, 3, 62]
And a word list containing corresponding words:
list2 = ['cat', 'dog', 'turtle', 'fox', 'elephant', 'eagle', 'scorpion']
i.e. there are 40 cats, 62 dogs, etc.
Data above is merely for representation. Each value in list1
is assigned an English dictionary word in list2
corresponding to the indexes i.e. index 0 of the first list corresponds to index 0 of the second list.
How can I be sure that in a for-loop, if I call list1.index(i) where i is 62, it would return me eagle first, and then when the for-loop is executed again, it would skip the first 62 and proceed to the second 62 and return me scorpion?
Upvotes: 1
Views: 61
Reputation: 239693
You can zip
both the items and iterate together to get the corresponding values together, like this
>>> for number, word in zip(list1, list2):
... print(number, word)
...
...
40 cat
62 dog
0 turtle
5 fox
8 elephant
3 eagle
62 scorpion
Or you can use enumerate
to get the current index of the item, from the list being iterated and use the index to get the corresponding value from the other list
>>> for index, number in enumerate(list1):
... print("index :", index, number, list2[index])
...
...
index : 0 40 cat
index : 1 62 dog
index : 2 0 turtle
index : 3 5 fox
index : 4 8 elephant
index : 5 3 eagle
index : 6 62 scorpion
Upvotes: 4