We start Day 12 by introducing two useful Python looping tools.
More Pythonic Looping Using zip() and enumerate()
00:00 Yesterday, I mentioned that in other programming languages, for loops are normally done differently, but in Python we have the Python way. However, sometimes you get to a problem, something you’re trying to create a loop for where you feel like you say, ah, in this situation I do need that integer, that index 0, 1, 2, 3, 4.
00:22 Often this happens if, for example, you want to print it out, you want that number, you want to print out 1, 2, 3, 4 as your loop goes through. Or maybe you have two separate iterables and you want to loop through them at the same time and you say, ah, well I’ve got two of them.
00:38 I want to put them all in the same for loop. How do I do this? Let me revert back to looping through numbers and then using that as an index to fetch items.
00:49 You may be tempted to do that, but Python, because Python has its own Python way of looping, wants to stick to the iterator protocol. So there are tools that come in to rescue you in these cases.
01:03
And two of the most important tools are the zip()
and the enumerate()
. We treat them as functions. They’re technically classes, but let’s treat them as functions.
You must own this product to join the conversation.