6. Loop Syntax
6.1. for loops
A loop is initialized with the keywords for
and in
. In the first line, you must create a loop variable (the variable that changes each loop iteration) and the iterable object to loop through. This line must end with a colon. Subsequent code must be indented with 4 spaces. The loop variable can be named anything. The iterable object must be an existing object.
The first line of a for loop should look like:
1for loop_variable in interable_object:
Below are syntax examples of how to loop over common data structures.
6.1.1 Looping over list elements
1# Syntax2for element in list_object:3 # <code applied to each element in list_object>
In each iteration, element
will equal an item in list_object
.
6.1.2 Looping over indices
1# Syntax2for i in range(0,11):3 # <code applied in each iteration>
In each iteration, i
will equal a number 0 to 10. You can use i
to index a list or nested list.
6.1.3. Looping over dictionaries
1# Syntax2for key_name, dict_value in dict_object.items():3 # <code applied to each list in dict_object>
key_name
and dict_value
are both loop variables equal to the key and value of the dictionary, respectively. items()
is a dictionary object method needed to make the loop work.