How can the range() function return a list of numbers incremented other than 1?


#1

Question

By default, the range() function returns a list of numbers incremented by 1. Is it possible to have the numbers increment by another value?

Answer

The range() function can be provided with three parameters. The first parameter is the starting number for the list. The second is the end value for the list (the list will stop before this number). The final value is the value used for the increment. By default, the value is 1 but it can be changed to any number greater than 0.

The following examples show two ranges - one where the numbers are incremented by 2 and the other incremented by 5.

by_two = range(1, 20, 2)
by_five = range(1, 20, 5)