Useful objects for loops
Below are three useful built-in objects that are often used with for
loops.
range()
If you would like to simulate a traditional “counter” style C++ for
loop, you can iterate over a range
sequence object/type instead.
>>> for i in range(0, 10):
... print(i)
If you run the example above, you will find that range(0, 10)
generates a sequence of numbers from 0 (inclusive) to 10 (exclusive).
The first parameter (start
) is optional, and defaults to 0. range(10)
is equivalent to range(0, 10)
>>> for i in range(10):
... print(i)
There is also an optional third step
parameter. A bit like in C++, it controls how much you increment the counter after each step.
>>> for i in range(0, 10, 2):
... print(i)
TIP: If you need a list
of numbers, then just convert range
to a list
!
>>> print(range(0, 5))
>>> print(list(range(0,5)))
enumerate()
Sometimes you may need both the index and the element in the list in a for
loop.
[US Billboard Hot 100 Chart Week of October 3, 2020]
# | Title |
---|---|
1 | Dynamite |
2 | WAP |
3 | Holy |
4 | Laugh Now Cry Later |
enumerate()
will provide you with the index (starting at 0 by default) as well as the element in the list.
>>> top_hits = ["Dynamite", "WAP", "Holy", "Laugh Now Cry Later"]
>>> for (position, title) in enumerate(top_hits):
... print(f"At number {position} we have {title}!")
...
At number 0 we have Dynamite!
At number 1 we have WAP!
At number 2 we have Holy!
At number 3 we have Laugh Now Cry Later!
Oops! The Billboard Chart does not have a position #0! Let’s fix that.
You can either add 1
to the position
variable…
>>> for (position, title) in enumerate(top_hits):
... print(f"At number {position + 1} we have {title}!")
...
Or give enumerate
an optional second argument to tell it to start the index at 1
.
>>> for (position, title) in enumerate(top_hits, 1):
... print(f"At number {position} we have {title}!")
...
zip()
zip()
is easier explained with an example.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> print(list(zipped))
[(1, 4), (2, 5), (3, 6)]
>>> for (a, b) in zip(x, y):
... print(f"{a}, {b}")
...
1, 4
2, 5
3, 6