In this section, we will learn what the for loop is and how to use it in Python.
What is Python for loop?
The for loop is used to loop through a sequence like a range of numbers, a list, a tuple, a dictionary or any other iterable objects and return its elements as a result.
So in short, if there’s an object (an iterable one) and it contains a bunch of elements, we can use the for loop in order to get each element of that object and run any sort of operations that is needed on top of the element.
Note: we did not cover the objects and classes yet, but in short, an iterator object is an object that implemented a protocol called iterator protocol which allows Python tools like `for` loop to access the element of that object as a result. By default, objects like `list`, `tuple`, string, and dictionary implemented this protocol and that’s why we can use for loop to iterate through the elements of mentioned objects.
Python for Loop Syntax
A for loop is nothing but a block of code and an expression on top of it. The expression is the part where we put an iterator object that wants to get its elements. After that, comes the body of the for loop where we put a set of instructions to be executed per each element of the target iterator object.
Here’s the syntax of the for loop:
for variable in iteratorObject: #body…
`for`: in order to create a for loop, we start with the keyword `for`.
`variable`: After the keyword `for` comes a variable name where each element of the target iterator object will be assigned to that variable. We can then use this variable within the body of the for loop in order to access the returned element of the iterator object. Note that the `variable` is also accessible outside the body of the loop too.
`iteratorObject`: This is the iterator object (like a list, tuple, dictionary etc.) That we want to iterate through its elements.
`in`: between the `variable` and `iteratorObject` we put the keyword `in`.
`:`: After the `iteratorObject` comes the colon `:` that declares the beginning of the for loop.
After that, any indented line below the for loop becomes part of the for loop.
Example: using for loop to iterate an array
li = ["Jack","John","Omid","Elon"] num = 0 for value in li: num +=1 print(f"{num}: {value}")
Output:
1: Jack 2: John 3: Omid 4: Elon
How does for loop work?
The `li` here is the iterable object and the `value` is the variable that each element of the list will be assigned to.
Now the for loop will iterate through the entire elements of the list and the body of the loop will be executed per each element that returns from the list.
Python range() Function
The Python range() function is used to create a sequence of numbers which can be used as the iterator object in for loops. A for loop then will iterate through the elements generated from the range() function and so we can use those numbers within the body of the for loop.
The function takes multiple different types of arguments but the one that we will be using in this section is:
range(number)
Where the number is the maximum number in the sequence that will be created using this function (starting from 0 up to the number that is set as the argument of this function).
For example:
range(20)
This call to the range() function will create a sequence of number starting from 0 up to 19 (the argument of the function declares how many numbers starting from 0 should be created in the sequence. So if the value is 20, that means starting from 0 to 20 numbers after that which will end to the value 19.)
Note: the range() function is explained in greater details in later sections.
Example: python for in range
for num in range(8): print(num)
Output:
0 1 2 3 4 5 6 7
Python for loop break statement
By default, a for loop will loop through the elements of an iterable object until its last element. After the last element, the loop will terminate.
But using the `break` statement, we can terminate a loop early if needed.
In the Python break section, we’ve explained this statement in greater details but in short, if we want to terminate a loop (a for loop, a while loop, etc.) We can simply call this statement within the body the loop and so the execution engine will terminate the work of the loop and continue to execute the instructions that come after the loop.
The `break` statement is a single statement and that means there are no other values that come along this statement.
Example: using break statement in for loop
names = ["Jack","Omid","John","Elon"] for name in names: if (name == "John"): break print(name)
Output:
Jack Omid
In this example, there’s an if statement within the body of the for loop. This if statement has a call to the `break` statement within its body and that will be triggered if one of the names in the list was equal to `John`.
Now the moment the name `John` returned from the list, the break statement is called and so the execution engine terminates the work of the for loop before it completely iterates through the entire elements of the list.
Python for Loop and else Statement
A for loop can also have an `else` statement as well.
The `else` statement is a block where we can put a set of instructions to be executed after the related `for` loop traversed the entire elements of the target iterable object. Basically, the `else` statement runs only if the `for` loop finished normally (without any call to terminator statements like `break` and `return`).
Python else Statement Syntax:
for expression: #body… else: #body…
`else`: in order to create an else statement for a for loop, we start with the keyword `else`. This keyword comes after the body of the related for loop.
`:`: we put a colon after the else keyword in order to declare the beginning of the body of the else statement. From here, any indented new line below the else statement will be part of the `else` block.
Example: using for Loop with else Statement in Python
names = ["Jack","Omid","John","Elon"] for name in names: print(name) else: print("There's no more element to iterate through")
Output:
Jack Omid John Elon
There’s no more element to iterate through
Python for loop continue statement
The `continue` statement is used when we want to stop the current iteration of the loop and move on to the next iteration of that loop.
Note: the continue statement will only terminate the current iteration of the loop, but it won’t stop the entire loop! Basically, we’re still in the loop, but the current iteration will be gone.
Example: using continue statement in for loop
for num in range(20): if num <10: continue print(num) else: print("There's no more element to iterate through")
Output:
10 11 12 13 14 15 16 17 18 19
There’s no more element to iterate through
Note that here as long as the value of the `num` variable is less than the value 10, a call to the continue statement will occur and this will cause the loop to terminate its current iteration and move on to the next iteration with a new number.
Python Nested for Loop
Using another for loop within the body of a for loop is called nested for loop.
This is especially useful when a for loop is iterating through a list that its elements are themselves lists! Using nested for loops, we can access the deepest elements in a multidimensional list.
Example: creating nested for loop in Python
li = [["Jack","Elon"], [1,2,3,4], [True,False]] for innerList in li: for value in innerList: print(value)
Output:
Jack Elon 1 2 3 4 True False
In this example, the first for loop returns the elements of the `li` list. We can see that these elements are themselves another list. So then we used another for loop within the body of the first loop in order to traverse the elements of the sub-lists and print them to the output stream.
Python for Loop vs While Loop
Both for loop and while loop could be used in order to run a block of code for several times. But the purpose of `for` loop is to mainly iterate through the elements of an iterable object and work on those elements within the body of the for loop.
But the while loop is designed to run a set of instructions as long as its condition is True! The condition of a while loop might have nothing to do with an iterable object!