In this article, we will explain you the below points about the Python range function with code examples.
- range function introduction and syntax
- Python range object indexing and slicing
- range with floating numbers
- Converting range object to list object
- range reverse
Quick Summary
The following is the quick summary about range()
function in Python.
Important notes about range function
1. Range object’s start
parameter is inclusive and stop parameter is exclusive.
2. Range function works with positive numbers, negative numbers but not floating points.
3. You can use the arange()
function from numpy module for floating range.
4. Indexing and slicing on range object is same as list’s indexing and slicing.
5. You can use range object with for loop to iterate over the list with index accessing.
6. in
operator can be used to do membership check in range object.
7. reverse range can be achieved using the builtin reversed()
method
Python range function
Python range()
function can be used to generate a sequence of numbers from a given start to a stop with the step.
Syntax:
range(start, stop, step)
Parameters:
Python’s range function accepts below three parameters.
Parameter | Explanation | Required | Default Value |
start | range starts at this value and it is inclusive | Optional | 0 |
stop | range end at this value and it is exclusive | Required | No default values |
step | at each iteration range will be incremented by step | Optional | 1 |
Return type:
It returns range class
type. You can access the given parameters directly as range.start
, range.stop
and range.step
.
range with stop parameter
If you pass only one integer parameter to range’s constructor, it will be considered as stop and start will be taken as 0 and step will be 1.
Code Thread:
for i in range(5):
print(i)
Output:
0
1
2
3
4
range with start and stop parameters
If you pass two parameters to range constructor it will treat first parameter as start and second parameter as stop. It will return a sequence of number from start to stop with the default step as 1.
Code Thread:
for i in range(1, 6):
print(i)
Output:
with range(1, 6)
, we will get numbers from 1 to 5 since stop(6) is exclusive.
1
2
3
4
5
range with step
In the above examples, we have used range() function with start and stop parameters. Now, we will use it with step
parameter as well.
Code Thread:
for i in range(1, 10, 2):
print(i)
Output:
with range(1, 10, 2), we are passing step as 2. It will add 2 to the current start at every step.
1
3
5
7
9
Negative numbers range
Range object also works the negative start, stop and step numbers.
Code Thread 1:
for i in range(-5, -1):
print(i)
Output:
-5
-4
-3
-2
Code Thread 2:
for i in range(-1, -10):
print(i)
Output:
#no output since -1 is greater than -10 and step is 1
Code Thread 3:
for i in range(-1, -6, -1):
print(i)
Output:
-1
-2
-3
-4
-5
range function with characters
The range function does not accept characters as parameters. However, you can use ord()
and chr()
functions to get range of characters.
Code Thread:
char_range = range(ord('a'), ord('z')+1)
print(list([chr(i) for i in char_range]))
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Accessing Range values with index and slicing
You can access range object values with indexing and slicing as same as list elements access.
Code Thread for Range indexing:
result = range(1, 11, 1)
# access third element with index number 2
third_element = result[2]
print('third_element:', third_element)
Output:
third_element: 3
Code Thread for range slicing:
result = range(1, 11, 1)
# access elements from 2 to 5 index number with slicing and slicing returns range object
part = result[2:6]
print('slice:', list(part))
Output:
slice: [3, 4, 5, 6]
range(length) to get List indexes
You can use the range()
function with stop
as length of the list to access the elements with the index number.
Code Thread:
employee_salaries = [100, 200, 400, 300, 600, 500]
for i in range(len(employee_salaries)):
print(employee_salaries[i])
Output:
100
200
400
300
600
500
Convert Python range object to list
Python range can be converted to list by passing range object to list() constructor as a parameter.
Code Thread:
print(list(range(10)))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
How to generate range reverse?
With the below two methods you can get reverse range in Python.
Method 1: using reversed() function
Alternatively, You can the in-built reversed()
function to get reverse iterator of range object.
Code Thread:
#range reverse using reversed function
def get_reverse_range(start, stop, step):
return reversed(range(start, stop, step))
start = 10
stop = 30
step = 5
reverse_range = get_reverse_range(start, stop, step)
print(list(reverse_range))
Output:
[25, 20, 15, 10]
Method 2: using __reversed__ method
You can also use __reversed__() method of range object to get the range in reverse order.
Code Thread:
#range reverse using __reversed__() method
def get_reverse_range(start, stop, step):
return range(start, stop, step).__reversed__()
start = 10
stop = 30
step = 5
reverse_range = get_reverse_range(start, stop, step)
print(list(reverse_range))
Output:
[25, 20, 15, 10]
How does range function works for Floating numbers?
In this section, we will see how to get sequence of floating point numbers.
Using standard range() for float – Throws error
The range()
function does not work with floating point numbers, it only works with positive and negative integers. If you pass floating numbers you will be thrown the TypeError.
Code Thread:
start = 1.0
stop = 2.0
step = 0.1
print(range(start, stop, step))
Output:
TypeError: 'float' object cannot be interpreted as an integer
Range of float numbers using numpy.arange()
To generate a range of floating point numbers, we can use arange()
function from numpy
the module as below. The return type of arange()
will be numpy.ndarray
.
Code Thread:
import numpy as np
start = 1.0
stop = 2.0
step = 0.1
result = np.arange(start, stop, step)
print(type(result))
print(result)
Output:
<class 'numpy.ndarray'>
[1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
Frequently Asked Questions
How to get range with inclusive numbers
In Python, the range object’s stop
parameter is exclusive. If you want to include it in the range then you just have to add 1 to the stop.
Code Thread:
def get_range_inclusive(start, stop, step):
return range(start, stop+1, step)
start = 10
stop = 31
step = 2
print(list(get_range_inclusive(start, stop, step)))
Output:
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32]
Using ‘in’ operator to check if element presents
Like lists in Python, you can use in
operator with range also for membership test as in the below code thread.
Code Thread:
range1 = range(1, 100)
if 45 in range1:
print(True)
else:
print(False)
Output:
True
Python concatenating two ranges
We can use chain
method from the itertools
library to iterate over the two ranges at a time and concatenate them.
Code Thread:
from itertools import chain
range1 = range(1,6)
range2 = range(6,11)
for element in chain(range1, range2):
print(element)
Output:
1
2
3
4
5
6
7
8
9
10
Python range start at 1
The range function accepts start
parameter. You can pass this start
parameter to get range object which starts from 1. If you don’t pass by default it will be 0.
Code Thread:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
-
What is range() function in Python?
The range() function in Python is used to create the sequence of numbers with given step. It takes start value, end value and step size as parameters and creates a range object. Syntax and code examples discussed.
-
Does range() returns a list?
No, range() function returns <class ‘range’>. You can use list() constructor to convert range to list in Python. Code examples are discussed in this blog.
Hope you have enjoyed reading this article about Python range function. For more insightful stories, follow codethreads.dev!!!