This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Repetition - for loops (2)

Below are two useful built-in objects that are often use with for loops.

(Note: You can just call them functions if you like. But in Python 3, they are actually classes/types and not functions).

range()

Say you need to print out all integers from 1 to 100. You probably do not want to write out the complete list of numbers by hand.

In addition to list and sequences, Python 3 offers a built-in range sequence object/type to achieve this.

for i in range(1, 10):
    print(i)

If you run the example above, you will find that range(1, 10) generates a sequence of numbers from 1 (inclusive) to 9 (inclusive). BEWARE: the sequence does not include the number 10! You will have to say range(1, 11) to get 1 to 10!

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. It controls how much you increment each the counter after each step. Trying the code below will explain it better:

for i in range(0, 10, 2):
    print(i)

For the C++/Java programmers among you, range simulates the conventional for loop in those languages. Python’s for loops are essentially the equivalent for-each loops in those languages.

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 item.

top_hits = ["Dynamite", "WAP", "Holy", "Laugh Now Cry Later"]
for (position, title) in enumerate(top_hits):
    print(f"At number {position} we have {title}!")

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}!")