26 Apr Range Function in Python
The range()
method in Python is usually used to return a fixed set of numbers between a given start integer to the end of an integer. We can have numbers like 0, 1, 2, 3, and 4, which is very useful since the numbers can be used to index into collections such as strings.
The Syntax of the Range Function
The range() function takes in three arguments(start, step, and stop), whereby we have two of these arguments that are optional(start and step) and the mandatory one is the stop
.
range(start, stop[, step])
We’ll demonstrate further how to use Range in the different examples below.
a. Generate Numbers with For Loop using One Parameter
We will implement a for loop by using only one parameter value (stop). Now, let’s find the range of numbers within 0 to 7 range, this should return 0 to 6. We might discover we have results showing 0, 1, 2, 3, 4, 5, and 6. The reason for this is that the range function does exclude the last value when computing its result.
1for i in range(7): 2 print(i)
Result
10 21 32 43 54 65 76
b. Generate Numbers with For Loop using Two Parameters
Now, we’ll generate numbers by using For loop with two parameters value(start and stop). Here, we have no step value.
1for i in range(1,5): 2 print(i) 3 4
Result
11 22 33 44
c. Reversed Range
The reversed function can be used with Range to perform the operation from the back. It is also possible to use positive or negative numbers as parameters in the range.
1for i in range(5, 1, -1): 2 print(i)
Result
15 24 33 42
Another Example
1s = 'Python' 2len(s) 3 4for i in reversed(range(len(s))): 5 print(i, s[i])
Result
15 n 24 o 33 h 42 t 51 y 60 P
d. How to create List, Tuple, and Set with Range
The range function is also applicable to use with other different methods whereby we have the list, set, and tuple.
List
1print(list(range(0, 20, 5)))
Result
1[0, 5, 10, 15]
Tuple
1print(tuple(range(0, 20, 5)))
Result
1(0, 5, 10, 15)
Set
1print(set(range(0, 20, 5)))
Result
1{0, 10, 5, 15}
No Comments