Python's "for" loops are single-purposed: they can loop over an iterable item-by-item. That's it.
The "for" loop itself can't loop in reverse or loop over multiple iterables.
For this reason, looping helpers are a VERY big deal in #Python.
Let's talk about looping helpers. 🧵
Want to loop over an iterable in the reverse direction? If it's a reversible iterable (lists, tuples, dictionaries, etc), you can use the reversed helper:
>>> colors = ["pink", "blue", "green"]
>>> for color in reversed(colors):
... print(color)
...
green
blue
pink
Note that the "for" loop isn't reversing here: reversed is!
The built-in reversed function accepts an iterable and returns a lazy iterable that provides each item from the original iterable in the reverse order.
>>> r = reversed(colors)
>>> next(r)
'green'
>>> next(r)
'blue'
Want to loop while counting upward? Python's enumerate function can help!
>>> for n, color in enumerate(colors, start=1):
... print(n, color)
...
1 pink
2 blue
3 green
Again the "for" loop isn't doing the work: enumerate is! The enumerate function returns a lazy iterable.
Need to loop over multiple iterables at once? That's what zip is for!
>>> colors = ["pink", "blue", "green"]
>>> animals = ["duck", "walrus", "monkey"]
>>> for color, animal in zip(colors, animals):
... print(color, animal)
...
pink duck
blue walrus
green monkey
The built-in zip function accepts any number of iterables and returns a lazy iterable that provides tuples of the n-th item from each of the given iterables (1st item from each, second from each, and so on).
Like enumerate, zip also pairs nicely with tuple unpacking.
What if you don't even have an "iterable" and you just need to increment or decrement numbers?
Python's range function can return an iterable that'll do that for you!
>>> for n in range(50, 300, 50):
... print(n)
...
50
100
150
200
250
These are just some of Python's many looping helpers.
Here are more examples from the itertools module:
• itertools.islice: stop after N items or skip the first N items
• itertools.chain: lazily "chain" iterables together
• itertools.takewhile: loop while a condition is true
You can also use generators & iterators to invent your own lazy looping helpers in Python.
This one acts like enumerate, but it counts downward:
def denumerate(iterable, start=0):
n = start
for item in iterable:
yield n, item
n -= 1
Want some practice with looping helpers? Try out @PythonMorsels! Lots of Python Morsels exercises involve both using and inventing own looping helpers.
If you enjoyed this thread:
1. Follow me, @treyhunner, for more of these 2. Retweet to share with others
Let's talk about what these methods do and why I recommend these ones first. 🧵
1️⃣ The string join method accepts an iterable of strings to join together.
It should be called on the separator you'd like to join by (e.g. " ", "\n", ",", ""). This is a string method: it's " ".join(my_list) and not my_list.join(" ").