×

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 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.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.

Loan Calculator using PyQt5 in Python

In the following tutorial, we will learn how to build a Loan Calculator application using the PyQt5 library in the Python programming language. So, let's get started. Introduction to the code: The heading...

4 minutes read.