The Python range() function returns an immutable sequence of integers between a given start and endpoint, incrementing by a given amount.
Python range Syntax
Here’s the syntax for the Python range() function:
range(start, stop, step)
Note that:
- start is the integer to start incrementing from – it will be included in the range
- If it is not supplied, it will be assumed to be 0
- stop is the integer to end the range at – it will NOT be included in the range – the range will end before the stop value
- If start and stop are the same, an empty range will be returned
- step is the integer amount each value in the range is incremented by
- Defaults to 1 if not specified
- Only integers are supported for all values
- The range() function will return an immutable sequence of integer values
- Immutable means that the contents of the sequence cannot be changed
Examples
Here are some examples for using the range() function:
Creating and Looping Over a Range of Integers from 0 to 4
myRange = range(4) for myNum in myRange: print(myNum)
Note that: – The result of the range() function has been assigned to the variable myRange – Each value in the generated range is assigned to the loop variable myNum and printed using a python for statement – As no start or step have been specified for the range() function, they have defaulted to 0 and 1 respectively
The above example will output:
0 1 2 3
Creating and Looping Over a Range of Integers from 10 to 30, in Increments of 5
myRange = range(10, 30, 5) for myNum in myRange: print(myNum)
Note that:
- We have supplied start, stop and step values to the range() function
The above example will output:
10 15 20 25
Creating and Looping Over a Range of Integers from 50 to 30, Decrementing by 2
Negative integers can also be supplied. Using a negative step will decrement instead of incrementing when generating the range values.
myRange = range(50, 40, -2) for myNum in myRange: print(myNum)
The above example will output:
50 48 46 44 42
Conclusion
Creating a range of numbers can be useful for looping over a series of known values or an array of a known size. Looping over a range can be used to perform actions on each value in the range, simplifying making calculations.