Python provides the
range() function in order to create sequences. These sequences can be used with different loop types like while, for, etc in order to iterate over items. What makes the range() method useful is it can be used to create a range without the overhead of creating and initializing one by one. The range() method is compatible with loop types where range() provides lightweight sequences.
range() Method Syntax
range() method has the following syntax.
- START is the starting value for the sequence. The START is optional and if not specified 0 is used as start value implicitly.
- STOP is the stopping or end value for sequence. The STOP parameter should be specified and required.
- STEP is the incrementing value where starts from START and ends STOP. The STEP is optional where if not specified it is assumed as 1 implicitly.
Create Sequence Between Start and End Numbers
The most popular and basic usage for sequence creation is providing the start and end numbers. In the following example, we start the sequence from 10 and iterate to 20.
x = range(10,20) for a in x: print(a)
10 11 12 13 14 15 16 17 18 19
Create Sequence Between 0 and Specified End Numbers
The START parameter is popular specified but it is an optional value. If the START is not specified 0 is used as START value. We just provide the STOP value which is 10.
x = range(10) for a in x: print(a)
0 1 2 3 4 5 6 7 8 9
Create Sequence Between Start and End Numbers with Specified Increment Value
The default step or incremental value for the range() method is 1. But this implicit value can be changed to different one by explicitly specifying it as the 3rd parameter to the range() method. In the following example we create a sequence from 0 to 18 by incrementing 3. Simply the increment value or step is 3.
x = range(0,18,3) for a in x: print(a)
0 3 6 9 12 15
Create Negative Sequences with range()
The range() function can be used to create negative sequences by providing negative steps. Also the START value should be higher then the STOP value as the sequence iterates backward. In the following example we start the negative sequence or decremental sequence from 4 to the -6 by decrementing with -2.
x = range(4,-6,-2) for a in x: print(a)
4 2 0 -2 -4