Python for Loop Increment
Introduction
In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.
In this article, we will understand loop increment. Let's look at how to handle the increment in Python for-loops. Let's look at it using the example below.
Example:
list_ = [6, 5, 3, 8, 2, 7, 9]
for k in range(len(list_)):
print(list_[k])
k += 2
Output:
[Running] python -u "d:\Programming\Python\test.py"
6
5
3
8
2
7
9
[Done] exited with code=0 in 0.352 seconds
The preceding example demonstrates this peculiar behavior of the for loop as the for loop in Python is a for-in loop rather than the conventional C style for loop, which is for (k =0; k <n; k++). The for-in loop is comparable to the for each loop in other programming languages. However, there are only a few ways to regulate the repetition in the for loop. Some of them are as follows:
Using range() Function
range() enables the user to create a sequence of numbers inside a specified range. Depending on how many arguments the user passes to the function, the user can choose where that series of values will begin and stop, as well as how large the gap between one number and the next is.
- Syntax: range (start, stop, step)
- Parameters:
- start: integer from which the sequence of numbers should be returned
- stop: number before which the integer sequence is to be returned
- step: integer value that influences how much every integer in the sequence grows
- Returns: a list
We can utilize the range function because the third parameter indicates the step.
Example 1: Increasing the iterator by one.
Code:
for k in range(10):
print (k)
Output:
[Running] python -u "d:\Programming\Python\test.py"
0
1
2
3
4
5
6
7
8
9
[Done] exited with code=0 in 0.284 seconds
Example 2: The iterator is being incremented by an integer number n.
Code:
# Increase the value
n = 4
for k in range(0, 42, n):
print(k)
Output:
[Running] python -u "d:\Programming\Python\test.py"
0
4
8
12
16
20
24
28
32
36
40
[Done] exited with code=0 in 0.324 seconds
Example 3: The iterator is being decremented by an integer number -n.
Code:
# Decreasing the value
n = -4
for k in range(40, 0, n):
print(k)
Output:
[Running] python -u "d:\Programming\Python\test.py"
40
36
32
28
24
20
16
12
8
4
[Done] exited with code=0 in 0.304 seconds
Example 4: Increasing the iterator by n exponential values. List comprehension will be used.
Code:
# The value of exponential
n = 3
for k in ([n**x for x in range(10)]):
print(k)
Output:
[Running] python -u "d:\Programming\Python\test.py"
1
3
9
27
81
243
729
2187
6561
19683
[Done] exited with code=0 in 0.365 seconds
Using While Loop
The Python While Loop is utilized to execute a set of statements continuously until a condition is met. When the condition is met, the line immediately following the loop in the program is performed.
While we cannot directly increase or decrease the iteration value within the body of the for loop, we may use the while loop to accomplish this.
For Example
Code:
# Utilizing while loop
list_of_value = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
k = 0
while(k <len(list_of_value)):
print(list_of_value[k], end = " ")
# Increasing the value of k
# within the loop will cause
#it to change when the
#condition is checked.
k += 2
Output:
[Running] python -u "d:\Programming\Python\test.py"
5 7 9 11 13 15
[Done] exited with code=0 in 0.341 seconds
Using List Slicing
We generally iterate through a list directly in Python, as demonstrated below.
For example:
my_List = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for elmt in my_List:
print(elmt, end=" ")
Output:
[Running] python -u "d:\Programming\Python\test.py"
5 6 7 8 9 10 11 12 13 14 15
[Done] exited with code=0 in 0.332 seconds
We can obtain consecutive values from the list using this method. What if we needed to increase the iterator by two? We could use slicing in such circumstances. The following is the syntax for slicing a list.
new_List= my_List [start_Index, end_Index,step]
In this case,
my_List is the input list, and new_List is the result of slicing my_List.
start_Index is the index of the item in my_List from which the elements in the new_List are added. If you want to include components right away, you can omit the start_Index empty.
end_Index is the index in my_List at which we finish including my_List entries in new_List. If you would like to include elements till the end, leave the end_Index empty.
step represents the number of elements in my_List that we skip before adding the next member to the new_List.
We can use slicing to specify the step as 2 to increase the iterator of the for loop by Two when iterating a list.
Code:
my_List = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print ("The items on the list are:")
for elmt in my_List:
print (elmt, end=" ")
print ("\nNow print elements at 2 intervals.")
for elmt in my_List[::2]:
print (elmt, end=" ")
Output:
[Running] python -u "d:\Programming\Python\test.py"
The items on the list are:
5 6 7 8 9 10 11 12 13 14 15
Now print elements at 2 intervals.
5 7 9 11 13 15
[Done] exited with code=0 in 0.308 seconds
You can see that we first displayed all the items on a list here. Then we made a slice of the previous list to add two elements to the for loop.
I would avoid using the slicing strategy when iterating over a list. This is because the sliced list takes up space as well. As a result, larger lists may require more memory space. Alternatively, you can utilize the range() method with indexing to retrieve the elements from the original list at 2 intervals.
Conclusion
In this post, we examined three techniques to increment a for loop in Python with the help of many examples. We've also shown why using the range() function rather than the slicing method is preferable.
I hope you had a wonderful time going through this tutorial. Stay tuned for the more helpful content.