×

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

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

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

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

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

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.