1

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.

2
  • 1
    Don't use list as variable name. Commented Nov 26, 2014 at 13:05
  • I'm not using list as a variable name, that was just as an example Commented Nov 26, 2014 at 13:06

1 Answer 1

3

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.