What is Python for loop and how to use it? for
loop in Python is a control flow statement that is used to execute code repeatedly over a sequence like a string
, list
, tuple
, set
, range
, or dictionary(dict) type
. In this article, I will explain for
loop usage, and syntax with several simple examples. The for loops are used when you have a block of python code you want to repeat several times. The for statement always combines with iterable objects like a set, list, range etc.
In Python, for
loops are similar to foreach
where you iterate over an iterable object without using a counting variable. In C/C++ languages to iterate over arrays, you should use a counting variable and manually increment it for each iteration, but Python for loop simplified this not to use a counter variable and provides a way to loop through each element in an iterable object. The loop starts from 0 and increments by 1. But, if you want you can also start the loop from ‘1’.
For Loop Key Points –
- Use
for
Loops to iterate a string, a list, a tuple, a set, a range, or a dictionary type. - Python for loop is similar to
foreach
loop not C like loops where you can loop through an index. - To come out of loop use
break
statement. - To skip the loop use
continue
statement. - To avoid errors use
pass
statement. - Optionally you can also use
else
with for loops.
Table of contents
- Syntax of For Loop
- Loop break & continue Statements
- Loop pass Statement
- loop else Statement
- Nested For Loop
- Loop through list
- Loop through range()
- Loop through set
- Loop through tuple
- Loop through dictionary (Dict)
1. Python For Loop Syntax & Example
Like any other programming language python for loops is used to iterate a block of code a fixed number of times over a sequence of objects like string, list, tuple, range, set, and dictionary.
Following is the syntax of the for loop in Python.
# Python for loop Syntax
for x in sequence:
#body of the loop
Here, x
is the variable that takes every value present in the sequence. Iteration will continue until we reach the last item in the sequence.
1.1 Python For Loop Example with String
A string contains a sequence of characters so, we can iterate each character in a string using for loop. Here we have taken ‘Hello
‘ as a string so, using for the statement we can iterate over each character in a string. For example,
# Iterate over the string
s="Hello"
for x in s:
print(x)
You will get the below output when you run the program.
# Output:
H
e
l
l
o
2. Loop break & continue Statements
2.1 For Loop using break Statement :
Sometimes you would like to exit from the python for
loop when you meet certain conditions, using the break statement we can break the loop based on a condition. For example,
With the break statement, you will early exit from the loop and continue the execution of the first statement after the for loop.
# Exit the loop using break statement
list=[10,20,30,40,50]
for x in list:
print(x)
if x == 40:
break
The above example exits for loop when the x value equals 40.
# Output:
10
20
30
40
Note that when you have for with the else block, exiting for with a break will not execute the else block, I will cover more about this in the below sections.
2.2 For Loop using continue Statement
Using the continue statement we can skip the current iteration of the loop and continue for the next iteration of the loop. For example,
# Skip the loop using continue statement
list=[10,20,200,30,40,300,60]
for x in list:
if x > 100:
continue
print(x)
Note that 300 is not displayed in the output as we have skipped the execution with continue when the x value is greater than 100.
# Output:
10
20
30
40
60
3. For Loop Using pass Statement
Use the pass
statement if you want for
loops with an empty body, where you wanted to complete the implementation in the future. Empty for is not a valid statement in python hence using will get an error, to avoid this error use a pass statement. If the pass statement is executed, the output will be nothing. For example,
# Using pass statement to avoid error
list=[10,20,30,40]
for x in list:
pass
4. For Loop Using else Block
Python allows the else keyword with for loop. The else block is optional and should be after the body of the loop. The statements in the else block will execute after completing all the iterations of the loop. If the program exits the loop only after the else block will execute. For example,
# For with else block
list=[20,30,10,40]
for x in list:
print(x)
else:
print("Task finished")
When you run the program output will be
# Output:
20
30
10
40
Task finished
As you learned above, you can use the break statement to exit the loop. In such cases, the else part will not be executed.
list=[20,30,10,40]
for x in list:
print(x)
if x == 10:
break
else:
print("Task finished")
Yields below output
# Output:
20
30
10
5. Nested For Loop
If a loop presents inside the body of another loop is called a nested loop. The inner loop will execute n number of times for each iteration of the outer loop. For example,
# Using nested loops
list1=[10,20]
list2=[5,10,20]
for x in list1:
for y in list2:
print(x,y)
Yields below output.
# Output:
10 5
10 10
10 20
20 5
20 10
20 20
5.1 Nested For Loop Using Break Statement
You can implement a nested for loop using a break statement. You can use break statement in nested loops to exit the innermost loop. Create two lists named list1
, and list2
, and then use an outer loop to iterate list1
and use an inner loop to iterate list2
. If elements of list1 and list2 are equal break the innermost loop and go to the outer loop.
# Using break statement in nested loops
list1=[10,20]
list2=[5,10,20]
for x in list1:
for y in list2:
if x == y:
break
print(x ,y)
Yields below output.
# Output:
10 5
20 5
20 10
6. Python For Loop Using List
As we know, a list contains a collection of values so, we can iterate each value present in the list using for loops. For example,
# Iterate over the list
courses = ["java", "python", "pandas"]
for x in courses:
print(x)
Yields below output.
# Output:
java
python
pandas
7. Python For loop Using range() Function
Using the range() function we can represent a sequence of values. So that, we can iterate every value present in the sequence using loops. For example,
Example 1
# Iterate over the range()
for x in range(5):
print(x)
When you run the program, you will get the following output.
# Output:
0
1
2
3
4
We have used range(5)
in the above example here, range(5) will return numbers from 0 to 4. It means the range()
function starts from 0 and increments by 1(by default) and ends before an end number.
Suppose we want 1(not only 1 but also any number) as a starting value it is possible to specify the starting value by adding a parameter range(1, 6)
, which means values from 1 to 5 (not including 6).
Example 2
# Using start parameter in range() function
for x in range(1,6):
print(x)
Yields below output.
# Output:
1
2
3
4
5
Example 3
In the range()
function, when you pass all three arguments, it will return a sequence of numbers, starting from the start number, increments by step number, and ends before an end number.
# Increment the step by 5
for x in range(5,50,5):
print(x)
Yields below output.
# Output:
5
10
15
20
25
30
35
40
45
Example 4
Using range() function in for loops to iterate through a sequence of values. Combination of range()
and len() function to iterate through a sequence using indexing. The easiest and most familiar method to access the index of elements in a for loop is using the list’s length. For every iteration, the index
will be increased, we can access the list with the corresponding index
. For example,
list=[20,30,10,40]
for index in range(len(list)):
value=list[index]
print(index,value)
Yields below output
# Output:
0 20
1 30
2 10
3 40
8. For Loop Using Python Set
A set
in Python is an unordered collection of items. so, the objects in a set are not ordered, indexes cannot be used to access them. Sets are an unordered collection, and so the values cannot be accessed through indexing. If we want to access the set values, The easiest way of iterating through a set is using for loop. In this article, you will learn how to iterate sets using a for a loop. For example,
# iterate over a set
courses={"java","python","pandas"}
for x in courses:
print(x)
Yields below output
# Output:
python
pandas
java
9. Python For Loop Using Tuple
A tuple
is a collection of values. so, we can iterate the values present in the collection, using a python for loop. Note that a tuple can have values of any type.
# iterate over a tuple
courses=("java","python","pandas")
for x in courses:
print(x)
Yields below output.
# Output:
java
python
pandas
Using a for loop we can also iterate over a dictionary. There are multiple ways to iterate and get the key and values from dict. Iterate over keys, Iterate over key and value. I will cover these with examples below.
10. Python For Loop Using Dictionary
10.1 For Loop through by Python Dict Keys
By default, if you use the examples explained above, you will get one key from the dictionary for each iteration.
# Loop through by Dict Keys
technology={"Course":"python","Fee":4000,"Duration":"60 days"}
for x in technology:
print(x)
Yields below output. Notice that it just displayed the keys from the dict.
# Output:
Course
Fee
Duration
10.2 Python for Loop through by Key and Value
Use dict.items() which returns a view object that gives a list of dictionary’s (key, value) tuple pairs. You can iterate over tuple to get the key and value.
# Loop through by Key and Value
technology={"Course":"python","Fee":4000,"Duration":"60 days"}
for key, value in technology.items():
print(key, value)
Yields below output
# Output:
Course python
Fee 4000
Duration 60 days
10.3 Use key to get the Value
Use dict[key]
to get the value of the key.
# Use key to get the Value
technology={"Course":"python","Fee":4000,"Duration":"60 days"}
for key in technology:
print(key,technology[key])
Yields below output.
# Output:
Course python
Fee 4000
Duration 60 days
10.4 Use dict.keys() & dict.values()
You can also get dict.keys() and iterate over each key, similarly, you can get the dict.values() and iterate each value.
# Use dict.keys() & dict.values()
technology={"Course":"python","Fee":4000,"Duration":"60 days"}
for key in technology.keys():
print('Key: '+ key)
for value in technology.values():
print('Value: '+value)
Yields below output.
# Output:
Key: Course
Key: Fee
Key: Duration
Value: python
Value: 4000
Value: 60 days
Conclusion
In this article, you have learned how to iterate objects such as string, list, range, tuple, dict and other objects using python for loop. As well, you have learned nested loops with examples.
Happy Learning !!
Related Articles
- Looping with if Statement in Python
- Break a Loop Statement in Python
- Iterate Over an Array in Python
- Looping with Continue And Break in Python
- How to Perform Decrement for Loop in Python
- How to Increment for Loop in Python
- Loop Enumerate in Python
- Get Counter Values in a for Loop in Python?
- Access Index in for Loop in Python
- How to Start Python For Loop at 1
- Iterate Over a List in Python
- Iterate Over a Dictionary in Python
- How to Write Python For Loop in One Line?
- How to terminate a script in Python?