for
Loops
for
Loop
The for loop is an example of an iteration loop. This means it iterates (i.e. walks) through every element of a sequence.
Syntax:
for target in range([start,] end[, increment]):
statement
[statements]
target
for
based upon the
range
given
range
for
loop to execute a set number of times.
start
end
end
). This value is
required.
increment
Two simple example:
n = 10
for i in range(n):
print(f"{i}, ", end="")
print()
prints:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
and:
n = 10
for i in range(n - 1, -1, -1):
print(f"{i}, ", end="")
print()
prints:
9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
for
Loops
These are the general rules to following when using for
loops:
Do not change the value of the target variable inside the loop. is important not because changing the target variable changes the loop execution, but because it doesn't change the loop execution (as it may in some other languages). Here is a simple example. The code:
n = 4
for i in range(n):
print(i)
prints:
0 1 2 3
The code:
n = 4
for i in range(n):
print(i)
i = n
also prints:
0 1 2 3
Clearly, changing the value of the target variable i
has
no effect on when the loop stops executing. This is because Python
generates the sequence of values the loop is to iterate through only
first time the for
is executed. This sequence cannot be
changed by any code within the body of the for
.
Do not change the contents of any of the sequence (start
,
end
, increment
) values inside the loop. The
code:
n = 4
for i in range(n):
print(i)
n = 0
also prints:
0 1 2 3
Again, this is because Python generates the sequence of values the
loop is to iterate through only first time the for
is
executed. Changing any of the sequence (start
, end
,
increment
) values inside the loop has no effect on the
loop's outcome.
Do not use of any of the sequence (start
, end
,
increment
) variables` as the target
variable. The code:
n = 4
for n in range(n):
print(n)
also prints:
0 1 2 3
but it's simply poor programming practice to reuse a variable for very different purposes. It also becomes difficult to produce output like:
0 of 5 1 of 5 2 of 5 3 of 5
if the target variable and the end variable are the same variable. (Simple sample solution using different target and end variables:)
n = 4
for i in range(n):
print(f"{i} of {n}")
Note that breaking these rules does not violate Python syntax - all these
sample codes still execute without error - but they demonstrate a lack of
understanding of how for
loops in Python actually work.
for
vs while
Loops
All for
loops can be rewritten as while
loops,
but the reverse is not true. for
loops should used when:
while
loops should used when:
for
loop is limited to iterating through a sequence and cannot use any other
conditions
for
Loops with Strings and Lists
A for
loop allows you to loop item by item all the way
through a sequence of items. This means that you can use the for
loop to:
Don't mix the two uses together. Example:
You have a simple list:
numbers = [7, 3, 0, 2]
and you are asked to count the number of 0s in the list. Here is a typical wrong way to do it:
for i in numbers:
if numbers[i] == 0:
zero_count += 1
This is wrong because i
is not an index. The i
in each iteration of the loop contains the values in the list numbers
one after another. Thus the line
if numbers[i] == 0:
is executed as this:
if numbers[7] == 0: ... if numbers[3] == 0: ... if numbers[0] == 0: ... if numbers[2] == 0: ...
which, of course, dies on the first try, because there is no element of numbers
with the index 7.
Here are two correct approaches:
By index
for i in range(len(numbers)):
if numbers[i] == 0:
zero_count += 1
In this example i
is an integer index that goes from 0 to
1 less than the length of the list numbers
. The range
function is necessary to generate the sequence of index values.
By value
for value in numbers:
if value == 0:
zero_count += 1
In this example value
becomes each of the actual values
in the list on each iteration of the loop. Note the lack of []
after value
- it has no need for an index. numbers
is not even referenced in the body of the loop.
The following code performs more work than is necessary:
for i in range(n):
if i == 0:
# process the first value
v = int(input("First value: "))
elif i == n - 1:
# process the last value
v = int(input("Last value: "))
else:
# process intermediate value
v = int(input("Next value: "))
Although this code 'works' in the sense that it correctly asks the user for all values that it should, it is the programming equivalent of children constantly asking their parents, "Are we there yet?", on a car trip. The loop is checking for very specific occurrences that happen only once, and should happen at the beginning or end of the loop.
A much better approach is to remove from the loop the code that is executed only once, and place it before or after the loop definition as appropriate:
# process the first value
v = int(input("First value: "))
for i in range(1, n - 1):
# process intermediate value
v = int(input("Next value: "))
# process the last value
v = int(input("Last value: "))
This principle applies to while
loops as well.