For Loop in Python
Unveiling the Power of for Loops in Python
In Python, the for loop is a versatile and fundamental construct that facilitates the iteration over a sequence of elements. Whether you’re working with lists, strings, or other iterable objects, the for loop simplifies the process of executing a set of statements for each item in the sequence. In this comprehensive guide, we’ll explore the syntax, functionality, and best practices associated with for loops in Python.
What Is a for Loop?
A for loop is a Python statement which repeats a group of statements a specified number of times. You can iterate over any object that is iterable, such as a list, tuple, string, and so on.
In Python, you can use the for loop in two ways:
- Iterating over a sequence: We can use a for loop to iterate over a sequence. The sequence can be a list, tuple, string, or any other iterable object.
- Iterating over a range: In Python, we can also use a for loop to iterate over a range. Using a for loop with a range() function, we can execute a set of statements for each item in a range.
Syntax of for Loop
The syntax of the for loop in Python is:
for val in sequence:
Body of for
for val in sequence:
Body of for
Here, val
val
is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Structure of for Loop
-
Initialization: In this step, we initialize the variable
val
val
with the first item in the sequence. This is the first item in the sequence.Syntaxfor val in sequence:
Syntaxfor val in sequence:
Here,
val
val
is the variable that takes the value of the item inside the sequence on each iteration. -
Condition: In this step, the
val
val
variable is checked to be less than or equal to the last item in the sequence. If it is true, the body of the for loop is executed. Otherwise, the loop terminates.Syntaxfor val in sequence:
Syntaxfor val in sequence:
Here,
val
val
is the variable that takes the value of the item inside the sequence on each iteration. -
Body: The body of the for loop is separated from the rest of the code using indentation.
Syntaxfor val in sequence: Body of for
Syntaxfor val in sequence: Body of for
Here,
Body of for
Body of for
is the body of the loop. It can contain one or more statements. It is executed once for each item in the sequence. -
Increment/Decrement: In this step, the variable
val
val
is incremented or decremented. The next item in the sequence is assigned to the variableval
val
. This continues until the last item in the sequence is reached.Syntaxfor val in sequence: Body of for
Syntaxfor val in sequence: Body of for
Here, Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Example: Python for Loop
# for loop
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
# for loop
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
C:\Users\Your Name> python for_loop.py
The sum is 48
C:\Users\Your Name> python for_loop.py
The sum is 48
In this program, we have used the for loop to iterate over a list and calculate the sum of numbers. We initialize the sum
sum
variable to zero and iterate over each element of the list using a for loop and add it to the sum
sum
variable. Finally, we print the sum
sum
variable which contains the sum of numbers in the given list.
range function
range()
range()
function
The range()
range()
function is used to generate a sequence of numbers. It returns an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j)
range(i, j)
produces i, i+1, i+2, ..., j-1
i, i+1, i+2, ..., j-1
. Start defaults to 0, and stop is omitted! range(4)
range(4)
produces 0, 1, 2, 3
0, 1, 2, 3
. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement). For example, range(1, 5)
range(1, 5)
produces 1, 2, 3, 4
1, 2, 3, 4
. range(6, 1, -1)
range(6, 1, -1)
produces 6, 5, 4, 3, 2
6, 5, 4, 3, 2
.
Syntax of range()
The syntax of the range() function is:
range(start, stop[, step])
range(start, stop[, step])
range()
range()
takes three arguments.start
start
is the starting number of the sequence. It defaults to 0 if not specified.stop
stop
is the last number of the sequence. It does not include this number. Therange()
range()
function goes up tostop - 1
stop - 1
.step
step
is the difference between each number in the sequence. It defaults to 1 if not specified.- The
range()
range()
function only works with the integers. Float is not allowed. If you need a range of floats, you can use thenumpy
numpy
library. - It returns a range object. You need to convert it to a list to see the sequence of numbers.
Example: range() function
# range() function
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
# range() function
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Output:
C:\Users\Your Name> python range_function.py
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
C:\Users\Your Name> python range_function.py
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
In this program, we have used the range()
range()
function to generate a sequence of numbers. We have passed one, two, and three arguments to the range()
range()
function. When we pass only one argument, it starts generating numbers from 0 and stops before the specified number. When we pass two arguments, it starts from the first argument and stops before the second argument. The third argument is the step size. The range()
range()
function increments the number by the step size until it reaches the second argument. The third argument is optional. If we do not specify the step size, it increments the number by 1.
In the above example, we have converted the range object to a list using the list()
list()
function. The list()
list()
function converts the range object to a list.
For Loop with else
For loops also have an else
else
clause which most of us are unfamiliar with. The else
else
clause executes after the loop completes normally. This means that the loop did not encounter any break
break
statement. The else
else
clause won’t execute if the loop breaks prematurely.
Syntax of for loop with else
The syntax of the for loop with the else
else
clause is:
for val in sequence:
Body of for
else:
Body of else
for val in sequence:
Body of for
else:
Body of else
The else
else
clause is only executed when your for
for
loop ends normally. This means that the loop
loop
didn’t encounter any break
break
or return
return
statement.
Example of for loop with else
# for loop with else
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
# for loop with else
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:
C:\Users\Your Name> python for_loop_else.py
0
1
5
No items left.
C:\Users\Your Name> python for_loop_else.py
0
1
5
No items left.
In this program, we have used the for
for
loop with the else
else
clause. The else
else
clause executes after the completion of the for
for
loop. The else
else
clause will be executed even if there is a continue
continue
statement inside the for
for
loop (but not if break
break
is encountered).
Iterating by Sequence Index
In Python, we can also access the sequence items using the index. The index starts from 0 in Python. We can use the index to iterate over a sequence. Consider the following example:
# iterating by index
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])
# iterating by index
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])
Output:
C:\Users\Your Name> python for_loop_index.py
I like pop
I like rock
I like jazz
C:\Users\Your Name> python for_loop_index.py
I like pop
I like rock
I like jazz
In this program, we have used the len()
len()
function to get the size of the list. The range()
range()
function then generates a sequence of numbers which is used to iterate over the list using the for
for
loop. We use the len()
len()
function in the range()
range()
function so that the for
for
loop runs the same number of times as the number of items in the list. We use the i
i
index to access each element in the list genre
genre
.
Iterating by Range Function
We can use the Python range()
range()
function to iterate over a sequence of numbers. It can be combined with the len()
len()
function to iterate over a sequence using indexing. Here is an example:
# iterating by range()
for i in range(0, 10):
print(i)
# iterating by range()
for i in range(0, 10):
print(i)
Output:
C:\Users\Your Name> python for_loop_range.py
0
1
2
3
4
5
6
7
8
9
C:\Users\Your Name> python for_loop_range.py
0
1
2
3
4
5
6
7
8
9
In this program, we have used the range()
range()
function to iterate over a sequence of numbers. We can also specify the start, stop, and step size as range(start, stop, step size)
range(start, stop, step size)
. We have used 0
0
as the start, 10
10
as the stop, and 1
1
as the step size in the range()
range()
function. It returns a sequence of numbers starting from 0
0
to 9
9
(10 numbers).
For Loop Through a String
Even strings are iterable objects, they contain a sequence of characters:
# for loop through a string
genre = 'Rock'
for i in range(len(genre)):
print("I like", genre[i])
# for loop through a string
genre = 'Rock'
for i in range(len(genre)):
print("I like", genre[i])
Output:
C:\Users\Your Name> python for_loop_string.py
I like R
I like o
I like c
I like k
C:\Users\Your Name> python for_loop_string.py
I like R
I like o
I like c
I like k
In this program, we have used the len()
len()
function to get the size of the string. The range()
range()
function then generates a sequence of numbers which is used to iterate over the string using the for
for
loop. We use the len()
len()
function in the range()
range()
function so that the for
for
loop runs the same number of times as the number of characters in the string. We use the i
i
index to access each character in the string genre
genre
.
You can also iterate over a string using a for loop without the range()
range()
function. For example:
# for loop through a string
genre = 'Rock'
for i in genre:
print("I like", i)
# for loop through a string
genre = 'Rock'
for i in genre:
print("I like", i)
Output:
C:\Users\Your Name> python for_loop_string.py
I like R
I like o
I like c
I like k
C:\Users\Your Name> python for_loop_string.py
I like R
I like o
I like c
I like k
In this program, we have used the for
for
loop to iterate over the string genre
genre
. We have not used the range()
range()
function. We have directly accessed each character using the i
i
index in the for
for
loop.
You can also use the for
for
loop to iterate over a sequence of lists. Consider the following example:
# for loop with else
digits = [0, 1, 5]
for i in digits:
print(i)
# for loop with else
digits = [0, 1, 5]
for i in digits:
print(i)
Output:
C:\Users\Your Name> python for_loop_list.py
0
1
5
C:\Users\Your Name> python for_loop_list.py
0
1
5
In this program, we have used the for
for
loop to iterate over a list digits
digits
. We have not used the range()
range()
function. We have directly accessed each element using the i
i
index in the for
for
loop.
Nested for Loop
In Python, a nested for
for
loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”:
Syntax of Nested for Loop
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something] # Optional
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something] # Optional
Example of Nested for Loop
# nested for loop
for i in range(1, 6):
for j in range(i):
print(i, end=' ')
print()
# nested for loop
for i in range(1, 6):
for j in range(i):
print(i, end=' ')
print()
Output:
C:\Users\Your Name> python nested_for_loop.py
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
C:\Users\Your Name> python nested_for_loop.py
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
In this program, we have used the nested for
for
loop to iterate over a sequence of numbers. We have used the range()
range()
function to generate a sequence of numbers. We have used the i
i
index to print the number of stars in each row. We have used the j
j
index to print the stars in each row. The j
j
index depends on the i
i
index. The value of the i
i
index is used to determine the number of stars in each row. The value of the j
j
index is used to print the stars in each row. The value of the j
j
index is incremented by 1 in each iteration of the inner for
for
loop. The inner for
for
loop is executed i
i
times for each iteration of the outer for
for
loop. The outer for
for
loop is executed 5 times. The inner for
for
loop is executed 1 time in the first iteration of the outer for
for
loop. The inner for
for
loop is executed 2 times in the second iteration of the outer for
for
loop. The inner for
for
loop is executed 3 times in the third iteration of the outer for
for
loop. The inner for
for
loop is executed 4 times in the fourth iteration of the outer for
for
loop. The inner for
for
loop is executed 5 times in the fifth iteration of the outer for
for
loop. The inner for
for
loop is executed 1 + 2 + 3 + 4 + 5 = 15 times.
Reverse Iteration/Loop
In Python, we can also iterate over a sequence in reverse, i.e., from the last item to the first item. We can do this by using the negative index. Consider the following example:
# reverse iteration
for val in range(10, 0, -1):
print(val)
# reverse iteration
for val in range(10, 0, -1):
print(val)
Output:
C:\Users\Your Name> python for_loop_reverse.py
10
9
8
7
6
5
4
3
2
1
C:\Users\Your Name> python for_loop_reverse.py
10
9
8
7
6
5
4
3
2
1
In this program, we have used the range()
range()
function to generate a sequence of numbers. We have used the negative index to iterate over the sequence in reverse. We have used -1
-1
as the step size in the range()
range()
function. It returns a sequence of numbers starting from 10
10
to 1
1
(10 numbers).
Conclusion
In this tutorial, we have learned about the for loop in Python. We have learned how to use the for loop to iterate over a sequence of elements. We have also learned how to use the range() function to iterate over a sequence of numbers. We have also learned how to use the for loop to iterate over a string and a list. We have also learned how to use the nested for loop to iterate over a sequence of numbers. We have also learned how to use the else clause with the for loop.
As you delve deeper into Python programming, experiment with different for loops, explore their applications in real-world scenarios, and use them to enhance the efficiency and clarity of your code. For more hands-on examples and in-depth tutorials, explore our resources on Python Central Hub!
Was this page helpful?
Let us know how we did