Python range() Function Usage
In Python 2.x, the range() function creates an integer list, commonly used in for loops.
Note:In Python 3, range() returns an iterable object (the type is an object) rather than a list type, so when printing, the list is not printed. For details, refer toPython 3 range() Usage Explanation。
Function Syntax
range(start, stop[, step])
Parameter description:
- start: Counting starts from start. Default is 0. For example, range(5) is equivalent to range(0, 5);
- stop: Counting ends at stop,but does not include stop. For example: range(0, 5) is [0, 1, 2, 3, 4] without 5
- step: Step size, default is 1. For example: range(0, 5) is equivalent to range(0, 5, 1)
Examples
>>>range(10) # From 0 to 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # From 1 to 10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # Step size is 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # Step size is 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # Negative numbers
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
The following is the use of range in a for loop, looping out each letter of example:
>>>x = 'example'
>>> for i in range(len(x)) :
... print(x[i])
...
r
u
n
o
o
b
Python Built-in Functions