1

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?

1 Answer 1

4
  1. 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
    
  2. 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
    
Sign up to request clarification or add additional context in comments.

1 Comment

Goodness me, thank you Sir, that works wonderfully. hangs head in shame now I will accept your answer as soon as the system allows me to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.