How do you increment a list in Python?

  1. HowTo
  2. Python How-To's
  3. for Loop Increment by 2 in Python

for Loop Increment by 2 in Python

Python Python Loop

Created: March-04, 2021 | Updated: March-15, 2021

In everyiteration, a for loop increases the counter variable by a constant. A for loop with a counter variable sequence of 0, 2, 4, 6 wouldincrement 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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Loop

  • Break Out of Multiple Loops in Python
  • Parallel for Loop in Python
    • Set and Get Environment Variables in Python
    • Break Out of Multiple Loops in Python
    How do you increment a list in Python?
    report this ad