Python | Equidistant element list
Last Updated :
06 Apr, 2023
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
strt = 5
end = 10
length = 8
test_list = [strt + x * (end - strt) / length for x in range (length)]
print ( "The Equidistant list is : " + str (test_list))
|
Output :
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
strt = 5
end = 10
length = 8
test_list = list (itertools.islice(itertools.count(strt, (end - strt) / length), length))
print ( "The Equidistant list is : " + str (test_list))
|
Output
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...