How the for loop works in Python
Overview
In any programming language, the for loop is used to traverse the given object in a sequential manner.
In Python, the for loop is not like that of other programming languages. It behaves like an iterator method and the difference has been illustrated in one of the examples below. The body of the loop is differentiated from the remaining code by indentation.
Syntax
for iterator_var in sequence:
loop_statements
Flow diagram
How to iterate specific times
To iterate over a sequence some specific times, we use the range() function, which gives a sequence with a default starting value of 0. It increments by 1 unless the step size is modified, and ends at the number specified in the arguments.
Suppose the arguments are range(2,14,2). The values would be 2,4,6,8,10,12. Below is an example:
for i in range(2,14,2):print(i)
Explanation
- Line 1: We run the
forloop with the starting index value,2, and ending value,14, of2increments every iteration. - Line 2: We print the
xvalue.
How to iterate over a string
Strings can also be used as iterable objects in Python in a for loop. Below is an example:
for n in range(7):print("value on n is {}" .format(n), end='\n')
Explanation
- Line 1: We run the
forloop with0-7range with1increment every iteration. - Line 2: We print the
nvalue with the string.
How to iterate over a list
We can also iterate over elements of a list. Below is an example:
breakfast = ["cereal", "bread", "yogurt"]for x in breakfast:print(x)
Explanation
- Line 1: We create a list with the name,
breakfast. - Line 2: We iterate the
forloop on the list. - Line 3: We print the
xvalue.
Iterator and Iterable
Iteration over the sequence in Python involves two types:
Iterable The object the loop is iterating over Iterator The object that does the actual iteration; it fetches the next item in the sequence
Thus, n = 7 will not stop our loop in the code below.
for n in range(7):print("value on n is {}" .format(n), end='\n')n = 7
Explanation
- Line 1: We run the
forloop with0-7range with1increment every iteration. - Line 2: We print the
nvalue with string. - Line 3: We assign the value,
n = 7.
Similarly, for loops can be used to iterate over a tuple, a dictionary, or even a set.
Free Resources