Python Morsels: Writing a for loop

Related Article:


You can use a for loop to loop over any iterable (iter-able). Anything you're able to iterate over can be looped over with a for loop.

Lists in Python are iterables. Here we have a variable favorite_fruits that points to list of strings:

>>> favorite_fruits = ["jujube", "pear", "watermelon", "apple", "blueberry"]

We can loop over (aka "iterate over") this favorite_fruits list using a for loop:

>>> for fruit in favorite_fruits:...     print(fruit)...jujubepearwatermelonappleblueberry

While executing that loop, Python takes each of the things inside of favorite_fruits list and gives us access to each of those items in order, using the variable name fruit. We're using that variable name to print each object (all strings in this case) out.

You can use this for anything that's iterable. An iterable is anything that can be looped over using a for loop.

Looping using indexes, the wrong way (don't do this)

Sometimes people write their for loops like this:

>>> for i in range(len(favorite_fruits)):...     print(favorite_fruits[i])...jujubepearwatermelonappleblueberry

There's a couple of reasons I don't recommend this.The first one is that PEP 8, the official Python style guide, recommends against this.Another reason is this only works with sequences.

A sequence is an iterable that you can index (using square brackets) starting from 0 until 1 less than the length of the sequence. Strings, tuples, and lists are all examples of sequences. Sets, dictionaries, files, generators, and lots of other iterables are not sequences.

The biggest reason not to use this is that we're doing a lot of unnecessary work here.We're using range(len(favorite_fruits)) numbers, representing indexes, in the variable i, and then using those indexes to then look each of the items up in our list.This extra work is like entering the backdoor of a building instead of the front door: you're still entering a door in either case but you have to walk much farther to go through the back door.

Not only that, but we're also focusing on the wrong thing: we're focusing on the index.We're giving a variable name, i, to the index. We're not giving a variable name to the most important thing here: the actual item we're working with.

Python's for loops don't have (or need) indexes

Python's for loop gives a name to each of the actual items we're working with (fruit in our case).

>>> for fruit in favorite_fruits:...     print(fruit)...jujubepearwatermelonappleblueberry

If something is important, it deserves a name. Python's for loops names the items themselves, not indexes.


When you're writing a for loop in Python, keep it simple, keep it as simple as possible.If you do need to count upwards as you loop, the built-in enumerate helper function can help you with that, and we can talk more about that later.

POst ID: 2647857978