This post is about the Python keyword for, not to mention in. If you’ve been reading these posts in anything like a linear way, you’ll remember them from Are You Feeling Loopy Yet?
Let’s hear it for for. Within the realm of Pythonland, it’s dull-looking but crucial in the larger scheme of things, sort of like Phil Coulson of comic book, film and TV fame. But boring-looking for wouldn’t be much without its cohort in. They make a pretty dynamic duo, kind of like Phil and Nick Fury, or Batman and Robin, or Laurel and Hardy, or Wayne and Garth, or Walter and Jesse. You get the idea. Python would be a lot less powerful without them.
If you want to move through a list, for example, nothing works better than “for i in x” or “for dog in hotdog” or “for beautiful in spacious_skies”. The foundation is always the for and the in. Here’s an example of the duo’s powers in action:
double =  sizes = [3, 4, 5, 7, 10, 13] for each_number in sizes: double.append (each_number*2) print (double)
Here’s what we get back:
[6, 8, 10, 14, 20, 26]
This bit of code takes every single number in the list called “sizes,” doubles those numbers, and sticks them into a different list called “double.” In the line “for each_number in sizes,” we’ve used “each_number” so it reads more like standard English, but we could just as well have used “i”. In fact, using “i” in these cases is something of a convention in Python, as in “for i in x.”
PS – For more information on for and in, I recommend Python.org’s excellent wiki tutorial. And if you’re looking for something a little more interactive, I recommend a short portion of How to Think Like a Computer Scientist.
Publicity photo of Stan Laurel and Oliver Hardy. Author: Hal Roach Studios https://commons.wikimedia.org/wiki/File:Laurel_and_Hardy.png