Skip to content
Related Articles

Related Articles

Specifying the increment in for-loops in Python
  • Last Updated : 01 Oct, 2020

Let us see how to control the increment in for-loops in Python. We can do this by using the range() function.

range() function

range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.

Syntax: range(start, stop, step)

Parameters:

  • start: integer starting from which the sequence of integers is to be returned
  • stop: integer before which the sequence of integers is to be returned
  • step: integer value which determines the increment between each integer in the sequence

Returns: a list



Example 1: Incrementing the iterator by 1.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

for i in range(5):
  print(i)

chevron_right


Output:

0
1
2
3
4

Example 2: Incrementing the iterator by an integer value n.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# increment value
n = 3
  
for i in range(0, 10, n):
  print(i)

chevron_right


Output:

0
3
6
9

Example 3: Decrementing the iterator by an integer value -n.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# decrement value
n = -3
  
for i in range(10, 0, n):
  print(i)

chevron_right


Output:

10
7
4
1

Example 4: Incrementing the iterator by exponential values of n. We will be using list comprehension.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# exponential value
n = 2
  
for i in ([n**x for x in range(5)]):
  print(i)

chevron_right


Output:

1
2
4
8
16

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :