Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let’s discuss a way in which this task can be performed.
Method : Using list comprehension This task can be performed using list comprehension, shorthand for the loop version of logic. In this, we just compute the range using division manipulation and extend it to increasing list forming equidistant list.
Python3
# Python3 code to demonstrate working of # Equidistant element list # using list comprehension # initializing start value strt = 5 # initializing end value end = 10 # initializing length length = 8 # Equidistant element list # using list comprehension test_list = [strt + x * (end - strt) / length for x in range (length)] # Printing result print ( "The Equidistant list is : " + str (test_list)) |
The Equidistant list is : [5.0, 5.625, 6.25, 6.875, 7.5, 8.125, 8.75, 9.375]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list test_list
Using itertools:
This code uses the itertools.count() function to generate a sequence of numbers starting from the value “strt” and incrementing by the value (end – strt)/length. Then it uses the itertools.islice() function to take the first “length” number of elements from that sequence and convert it into a list. The resulting list will be an equidistant list of numbers between the start and end values.
Python3
import itertools # initializing start value strt = 5 # initializing end value end = 10 # initializing length length = 8 # Equidistant element list using itertools test_list = list (itertools.islice(itertools.count(strt, (end - strt) / length), length)) # Printing result print ( "The Equidistant list is : " + str (test_list)) #This code is contributed by Edula Vinay Kumar Reddy |
The Equidistant list is : [5, 5.625, 6.25, 6.875, 7.5, 8.125, 8.75, 9.375]
Time complexity: O(n)
Auxiliary space: O(n) where n is the number of elements in the list.