Python Range
Python Range
In Python, there is a built-in function “range()“. The function outputs a sequence of numbers, with a pre-defined range.
It contains three arguments: start of range, end of range, and steps to take (e.g. 1, 2, 3 or 1, 3, 5 or 3, 6, 9). Only the second argument (end of range) is mandatory.
Note that when “range()” has only one argument, it declares the end of range and the method always starts from 0 and with 1 step increment by default.
The following is an example of the “range()” method.
num = range(5) print(num) # Output: range(0, 5)
The function creates a range type. But Python can convert it to a different data type, such as a list (or only print the output as a list).
num = list(range(5)) print(num) # Output: [0, 1, 2, 3, 4]
num = range(5) print(list(num)) # Output: [0, 1, 2, 3, 4]
The example below shows how to include a starting range point. Note that the last number does not print in the outcome.
num = list(range(4, 11)) print(num) # Output: [4, 5, 6, 7, 8, 9, 10]
The final argument is the step increment (increase). By default, the function always operates with a step of 1.
The following is an example of the method “range(), with all three arguments.
num = list(range(0, 15, 2)) print(num) # Output: [0, 2, 4, 6, 8, 10, 12, 14]
Range() with loops
The “range()” function works well with loops. This is a very common practice in Python.
Below is an example with a “for” loop.
for num in range(1, 6): print(num, "apples") # Output: 1 apples 2 apples 3 apples 4 apples 5 apples
An “if” statement (together with “continue”) can make the above more presentable (see below).
for num in range(1, 6): if num == 1: print(num, "apple") continue print(num, "apples") # Output: 1 apple 2 apples 3 apples 4 apples 5 apples