Next, let us look at the for loop. The for loop executes a block of code repeatedly until the condition in the for statement is no longer valid.
Looping through an iterable
In Python, an iterable refers to anything that can be looped over, such as a string, list or tuple. The syntax for looping through an iterable is as follows:
for a in iterable:
print (a)
Example:
pets = ['cats', 'dogs', 'rabbits', 'hamsters']
for myPets in pets:
print (myPets)
In the program above, we first declare the list pets and give it the members 'cats', 'dogs', 'rabbits' and 'hamsters'. Next the statement for myPets in pets: loops through the pets list and assigns each member in the list to the variable myPets.
The first time the program runs through the for loop, it assigns ‘cats’ to the variable myPets. The statement print (myPets) then prints the value ‘cats’. The second time the programs loops through the for statement, it assigns the value ‘dogs’ to myPets and prints the value ‘dogs’. The program continues looping through the list until the end of the list is reached.
If you run the program, you’ll get
cats
dogs
rabbits
hamsters
We can also display the index of the members in the list. To do that, we use the enumerate() function.
for index, myPets in enumerate(pets):
print (index, myPets)
This will give us the output
0 cats
1 dogs
2 rabbits
3 hamster
The next example shows how to loop through a string.
message = ‘Hello’
for i in message:
print (i)
The output is
H
e
l
l
o
Looping through a sequence of numbers
To loop through a sequence of numbers, the built-in range() function comes in handy. The range() function generates a list of numbers and has the syntax range (start, end, step).
If start is not given, the numbers generated will start from zero.
Note: A useful tip to remember here is that in Python (and most programming languages), unless otherwise stated, we always start from zero.
For instance, the index of a list and a tuple starts from zero.
When using the format() method for strings, the positions of parameters start from zero.
When using the range() function, if start is not given, the numbers generated start from zero.
If step is not given, a list of consecutive numbers will be generated (i.e. step = 1). The end value must be provided. However, one weird thing about the range() function is that the given end value is never part of the generated list.
For instance,
range(5) will generate the list [0, 1, 2, 3, 4]
range(3, 10) will generate [3, 4, 5, 6, 7, 8, 9]
range(4, 10, 2) will generate [4, 6, 8]
To see how the range() function works in a for statement, try running the following code:
for i in range(5):
print (i)
You should get
0
1
2
3
4