For loops#
Using for loops#
The main advantage of computer over human is that it can do repetitive tasks really well. So to realize the full power of python we need a way to ask a computer to repeat itself without repeating ourselves. The simplest way to achieve this is via a for loop.
Let’s say we have a list a_list = [1, 3, 7], and we want to print out the values of the list one by one. Our code may look like this:
# define our list of values
a_list = [1, 3, 7]
# print out values one by one
print(a_list[0])
print(a_list[1])
print(a_list[2])
1
3
7
Instead, we may ask python to “go through” the numbers in a_list one by one, and, at each step, print out the value of the current number. To put this idea into codes we need to use a for loop, like so:
for val in a_list:
print(val)
1
3
7
Conceptually, what python does given the above code is the following:
It starts with the first element of
a_listand assign it tovalIt performs the action specified in the indented block, using the current value of
valOnce it finishes executing the indented block, it steps into the next element of
a_listand assign it tovalIt then repeat step 2, i.e., perform the action specified in the indented block
Steps 3 and 4 are then repeated until all values in
a_listare exhausted.
Notably:
The colon
:is part of the syntax. You must end the first line of theforloop with a colon.We specify a dummy variable
valin the unindented line of theforloop, whose value changes every time we “step forward” in the loopThe
print()statement is indented. This is necessary so that python knows that theprint()statement needs to be executed every time we make a step forward
As another example, let’s say you want to add all the values in a_list together. To do so, we need to define a variable to hold the partial sum, and increment it every time we step through the loop. The resulting codes may look like this:
total = 0
for val in a_list:
total = total + val
print(total)
11
(NOTE: python actually has a built-in function sum() for this. The above is for illustrative purpose only)
Notice that:
We need to initialize our
totalvariable before stepping into the loop. The right value for our purpose istotal = 0We again define a variable
valto store the current member in the list that we are “stepping through”The line
total = total + valis part of the loop. It says that at every step, we add the current value oftotaland the current value ofvaltogether, then reassign the result tototalThe line
print(total)is outside of the loop. It is executed once after we finished looping througha_list
As a final example, let’s say you want to create a new list called sq_list, such that every member is the square of the corresponding value in a_list. Here is a for loop that performs such a task:
sq_list = []
for val in a_list:
sq_list.append(val**2)
print(sq_list)
[1, 9, 49]
I will let you figure out how to interpret the above codes yourself.
Enumerate as you loop#
Sometimes when you go through a list, you want to know the index of the current element in addition to its value. The enumerate() function can help you in such circumstance. An example:
for index, val in enumerate(a_list):
print("At index " + str(index) + " we get the value " + str(val))
At index 0 we get the value 1
At index 1 we get the value 3
At index 2 we get the value 7
Note that we defined two dummy variables on the same starting line of the loop. The index variable corresponds to the index of the current element (a count that starts from 0 and increase by 1 every time you step through the loop), while the val variable corresponds to the value of the current element
Range objects#
We have learned how to step through a list using a for loop, but up to now we have to construct the list by hands, which somewhat defeat the purpose of a loop. A better way to generate a regular sequence to loop through is to use of the range() objects.
The range() object can take between 1 to 3 arguments, each of which must be an integer. The meanings of the arguments are as follows:
if
range()is supplied with 1 argument, that argument is interpreted as the (exclusive) endpoint, and the sequence will start from 0 and increase by 1 until it hits the endpoint.if
range()is supplied with 2 arguments, the first argument is interpreted as the (inclusive) starting point and the second argument is interpreted as the (exclusive) end pointif
range()is supplied with 3 arguments, then the first two arguments are interpreted as above, while the last argument is interpreted as the step between consecutive outputs.
(Note that the arguments of range() resemble the syntax of the slicing object start:stop:step)
Some examples:
# start with 0, end with 6 (exclusive), incrementing in step of 1
for x in range(6):
print(x)
0
1
2
3
4
5
# start with 1, end with 5:
for x in range(1, 6):
print(x)
1
2
3
4
5
# start with 1, end with 5, increment in step of 2:
for x in range(1, 6, 2):
print(x)
1
3
5
It should be noted that a range() object has a different internal representation than a list() object. If you really want to convert a range object into a list, you’ll need to wrap it around a list() call. For example:
# the range object has a different internal representation and does not print out its value
print(range(1, 6, 2))
range(1, 6, 2)
# define a list by converting from a range object
a_list = list(range(1, 6, 2))
# The results behave like the list we know, e.g.,
print(a_list)
[1, 3, 5]