Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Working with Sequences Using range
The last sequence-related type introduced here is range. It has already appeared in examples that specify numeric ranges for for loops.
for n in range(10)
The expression range(10) creates a range. The following examples display the generated sequences as lists for clarity.
From 0 to the Value Before the Specified End
variable = range(end)
Example:
range(10)
↓
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
From a Start Value to the Value Before the End
variable = range(start, end)
Example:
range(10, 20)
↓
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
From a Start Value to the Value Before the End with a Step
variable = range(start, end, step)
Example:
range(10, 50, 5)
↓
[10, 15, 20, 25, 30, 35, 40, 45]
A range represents an ordered numeric sequence. It can be used in various situations, but it is most commonly used to specify the repetition range of a for loop.
for n in range(10):
print(n)
This code prints the values in the range sequentially.