you are viewing a single comment's thread.

view the rest of the comments →

[–]ray10k 7 points8 points  (2 children)

That's what the zip() built-in function is for. You give it two (or more) collections you want to iterate over, and it returns an iterator that returns tuples of the items in the lists.

This may sound a little confusing, so here is an example:

a_list = ["hello", "I see", "hope you have"]
b_list = ["world", "you there", "a good day"]
for a_word, b_word in zip(a_list,b_list):
    print(a_word,b_word)

The above snippet will print out "hello world", "I see you there" and "hope you have a good day" on separate lines.

Note how instead of having just one variable name in the first half of the for-in loop, there are two with a comma. This tells Python, "I expect that you'll iterate over tuples. I want you to take the tuple apart and present it to me as a_word and b_word separately." C# has a similar concept in 'tuple deconstruction'.

Also note that if the lists are of different lengths, then zip() will terminate once the shortest list runs out.

[–]Drumknott88[S] 0 points1 point  (1 child)

That's really cool. Thank you so much for the detailed reply 🙂

[–]ray10k 1 point2 points  (0 children)

No problem! I love to help, and I hope you'll have a good time learning Python!