Specifying the increment in for-loops in Python
Let us see how to control the increment in for-loops in Python. We can do this by using the 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)
- 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.
0 1 2 3 4
Example 2: Incrementing the iterator by an integer value n.
0 3 6 9
Example 3: Decrementing the iterator by an integer value -n.
10 7 4 1
Example 4: Incrementing the iterator by exponential values of n. We will be using list comprehension.
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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course