Looping through an iterable is the most basic and fundamental ability of any programming language.
Python’s for loop is at a first glance very straightforward, but just like with any other tool it can be used in multiple ways - these become handy when you start taking performance into account.
Here are 6 things to consider when you need to loop over something.
1. Maybe I don’t actually need a for-loop
For loops can be slow. There are many built-in methods optimized for specific tasks. Perhaps a better approach would be to simply use a built-in function. Let’s say you need to sum up a list of numbers.
|
|
You can either loop through the list and sum up the numbers.
|
|
Or, use a built-in sum() function.
|
|
2. I need both the index and the value
Traditional way is to index each item.
|
|
But Python offers a function that lets you access both values at the same time - enumerate(). It returns a tuple, which you can immediately unpack.
Thing I discovered recently is that you can pass another argument into enumarate, start
, and define a number from which you’d like to start (as arrays are 0-indexed).
|
|
3. I need to loop over multiple iterables at once
Using zip() function is very useful here. Achieving this through regular for-loop is very error-prone.
|
|
Now, if you increase numbers by one, you will get IndexError: list index out of range. Instead, you can use zip() function.
|
|
Sometimes though, you still need the error message in order to avoid bugs, for that you can pass another argument strict=True
(new from Python 3.10), and this will raise a ValueError: zip() argument 2 is shorter than argument 1.
|
|
4. Think Lazy & use a Generator
Let’s say you want to calculate how much time you spend on a specific task.
|
|
Another useful approach might be to use a generator with a sum() function.
|
|
Main difference - a generator is evaluated lazily - nothing happens until we call sum() on it. Thing to be aware of - objects are consumed when using the generator, which means if we were to print time_spent
again, the result would be 0.
5. Itertools
Functions creating iterators for efficient looping. Module that brings many functions to improve looping. So far I tried 3 of them and found them really useful.
-
islice()
|
|
-
pairwise()
|
|
-
takewhile()
|
|