Course contentsShow
← Python
Lesson 86 of 1,0602. Control Flow and LogicFree lesson

Customizing Loop Intervals with Step Arguments

Learners will be able to skip values within a range by providing a custom step increment to the range function.

Customizing Loop Intervals with Step Arguments

In this lesson, you will learn how to "skip" numbers in a sequence by providing a third argument to the range() function.

So far, you’ve used range() to generate a sequence starting from one number and ending at another. By default, Python counts upward by 1. However, if you need to count by twos, fives, or even backwards, you can use the step argument.

How the Step Argument Works

The range() function can actually accept three inputs: range(start, stop, step).

  • Start: Where the sequence begins (inclusive).
  • Stop: Where the sequence ends (exclusive).
  • Step: The amount to increment by each time.

If you don't provide a step, Python assumes it is 1. If you provide a custom number, Python will add that number to the current value during each iteration of the loop.

Practical Example

Imagine you want to print only the even numbers between 0 and 10. Instead of writing a complex if statement inside your loop to check for evenness, you can simply tell range() to skip every other number:

# Start at 0, stop before 11, increment by 2
for number in range(0, 11, 2):
    print(number)

Output:

0
2
4
6
8
10

Because we set the step to 2, Python starts at 0, adds 2 to get 2, adds 2 again to get 4, and so on. This makes your code much cleaner and more efficient than checking every single number individually.

You can also use negative numbers for the step if you want to count backwards, as long as your start is higher than your stop. For example, range(10, 0, -1) would generate numbers from 10 down to 1. Using the step argument allows you to navigate numeric ranges with precision, saving you from writing extra logic inside your loops.

Key Takeaway: Adding a third argument to the range(start, stop, step) function allows you to skip values and define a custom increment for your loops.