Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
The results of the script are used in blog article called
"Revisiting the Mechanism Behind the `for` Statement" hosted at
Purpose: The script measures the performance of iterating over all
elements in an iterable with two different implementation methods, namely
using Pythonic and non-Pythonic design patterns. See functions
`loop_pythonic` and `loop_with_indexes` for details.
Requirements: Python version >= 3.3
License: MIT License (see
from functools import wraps
from time import perf_counter
ITERABLE = range(1000000) # <-- change here e.g. ITERABLE = list(range(1000000))
def timeit(func):
"""Minimalistic decorator for timing the performance of `func`"""
def chronometer(*args):
t1 = perf_counter()
rv = func(*args)
t2 = perf_counter()
print(f"Elapsed time: {t2 - t1} s")
return rv
return chronometer
def loop_for(iterable):
"""Retrieve elements of `iterable` with the for-loop
Demonstrates the Pythonic way of iterating over objects.
for item in iterable:
return None
def loop_indexes(iterable):
"""Retrieve elements of `iterable` with indexes
Demonstrates non-Pythonic way of iterating over objects.
for index in range(len(iterable)):
return None
def loop_while(iterable):
"""Retrieve elements of `iterable` with the while-loop
Demonstrates the mechanism behind the for-loop.
_i = iter(iterable)
_loop = True
while _loop:
item = next(_i)
except StopIteration:
_loop = False
return None
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment