×

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.

  1. Syntax: range (start, stop, step)
  2. 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
  3. 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.


Related Topics

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Python List remove() method

Python List remove() method The list.remove () method in Python removes the item at the specified position in the given list. Syntax list.remove(x) Parameter x: This parameter represents the element you want to remove and accepts any type...

1 minute read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.