Python - How To for Loop Increment by 2 in Python

ID : 459

viewed : 233

Tags : PythonPython Loop

vote vote

98

In every iteration, a for loop increases the counter variable by a constant. A for loop with a counter variable sequence of 0, 2, 4, 6 would increment by 2 per iteration.

This article will introduce some methods to increment by 2 in the Python for loop.

Increment by 2 in Python for Loop With the range() Function

In this function, we use the range() function. It has three parameters, start, stop, and step. This function iterates from the start value and increments by each given step but not including the stop value.

The complete example code is given below.

for x in range(0, 12, 2):   print(x) 

If you are working in Python 2, you can also use the xrange() function.

Output:

0 2 4 6 8 10 

Increment by 2 in Python for Loop Using the Slicing Method

This method uses the slice operator : to increment the list values by 2 steps. In the code, the first digit represents the starting index (defaults to 0), the second represents the ending slice index (defaults to the end of the list), and the third represents the step.

The complete example code is given below.

my_list = [1,2,3,4,5,6,7,8,9,10] for x in my_list[1::2]:     print (x) 

Output:

2 4 6 8 10 

Be aware that this method copies the original list to a new memory space. It will have a bad speed performance if the list is huge.

  • Related HOW TO?