Getting Python range() to recognise a decimal eg. 70.555555

564 views Asked by At

Using Python 3.4 and I have a list which has numbers in it which have 8 decimal places or more (eg. -72.2373909452 and 175.33903215), and I need a way to separate them according to their number.

Original code looks like this:

for number in list:
    range_list=[]
    if number in range(x, y):
        range_list.append(number)

but for obvious reasons it doesn't work and doesn't add any numbers to the new list.

I also thought about multiplying the number first and then just having the range numbers between factors of ten, but as the number of decimal places is different between each number that isn't practical.

1

There are 1 answers

0
Dettorer On BEST ANSWER

If I understand well, you want to check if number is between x and y.

Just use comparisons then. The following has the same behavior the "number in range(x, y)" solution has with integers:

if x <= number < y:
    range_list.append(number)

Even if number is an integer, this sort of comparison is clearer and most likely faster than the solution involving range.

On a side note, you should define range_list outside of the for loop, otherwise you'll end up emptying the list with each loop:

range_list=[]
for number in my_list:
    if x <= number < y:
        range_list.append(number)