Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Specifying the increment in for-loops in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




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


Output:

0
1
2
3
4

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

Python3




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


Output:

0
3
6
9

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

Python3




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


Output:

10
7
4
1

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

Python3




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


Output:

1
2
4
8
16

Time complexity: O(n), where n is the number of iterations.
Auxiliary space: O(1), as only a constant amount of extra space is used to store the value of “i” in each iteration.


My Personal Notes arrow_drop_up
Last Updated : 22 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials