Skip to content
Related Articles

Related Articles

Python | Decimal step range in list

View Discussion
Improve Article
Save Article
  • Last Updated : 15 Jul, 2022

Sometimes, while working with a Python list we can have a problem in which we require to populate the list in a range of decimals. Integral ranges are easier to handle using inbuilt constructs, but having a decimal value to provide to range value doesn’t work. Let’s discuss a way in which this problem can be solved.

Method 1: Using list comprehension

One way to solve this problem is by using list comprehension which can solve this problem in an easier way by iterating the list and multiplying the range element to the index of the element.

Python3




# initializing start value
strt = 5
 
# initializing step value
step = 0.4
 
# using list comprehension
# Decimal step range
test_list = [strt + (x * step)
             for x in range(0, 5)]
 
# Printing result
print("The list after decimal range\
                value initialization : " + str(test_list))

Output:

The list after decimal range value initialization : [5.0, 5.4, 5.8, 6.2, 6.6]

Method 2: Using Numpy.linespace

The numpy.linspace() function returns number spaces evenly w.r.t interval. Similar to numpy.arange() function but instead of step it uses sample number.

Python3




import numpy as geek
 
# restep set to True
print("Decimal range value",
      geek.linspace(2.0, 3.0, num=5))

Output:

Decimal range value [2.   2.25 2.5  2.75 3.  ]

Method 3: Using Numpy.arrange

The np.arange([start,] stop[, step,][, dtype]), Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop) 

Python3




import numpy as np
 
# Printing all numbers from 1 to
# 2 in steps of 0.1
print(np.arange(1, 2, 0.1))

Output:

[1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!