Loops provide a means to perform the same action across multiple items. Multiple items are typically stored in a Python list
object. Any list-like object can be iterated over (e.g., tuples, arrays, dataframes, dictionaries). More information on loops can be found in the Software-Carpentry Python lesson on loops.1
1. https://swcarpentry.github.io/python-novice-inflammation/05-loop/index.html
To loop over a list. we use a for
statement. The basic for
loop looks like this:
for item in container:
# do something
The container
represents some iterable set of values (e.g., a list
). The item
represents a temporary variable that represents each item in the iterable. In the for
statement, the first element of the container is assigned to the temporary variable (in this example, item
). Everything in the indented block after the colon is then performed. When it gets to the end of the loop, the code assigns the next element in the iterable to the temporary variable and performs the steps over again.
# an example list of values to iterate over
l = [1, 2, 3]
# write a for loop that prints the value and its squared value
for i in l:
# print the current value
print(f"the current value is: {i}")
# print the square of the value
print(f"its squared value is: {i*i}")
# end of the loop, the
at the end creates a new line
print("end of loop, going back to the top
")
the current value is: 1
its squared value is: 1
end of loop, going back to the top
the current value is: 2
its squared value is: 4
end of loop, going back to the top
the current value is: 3
its squared value is: 9
end of loop, going back to the top
3.144.9.124