RealFL
RealFL

Reputation: 117

Delete all values in list outside of specified range python

I have a list (let's call it L1) with plenty of decimal values. How do I remove all values outside of some specified range while keeping all values within the range?
For instance, let's say I define my range as [-1, 1] and

L1 = [-2, 0.1, 0.75, 4] 

I would want my output to be a new list, i.e.

L2 = [0.1, 0.75]

I've heard there was a way to do this with numpy (though I can't find the SO question for the life of me), but I was wondering if there was another way, just using the built-in functions (of course if numpy is better for this sort of thing, then that's fine too).

Upvotes: 4

Views: 9421

Answers (5)

MSeifert
MSeifert

Reputation: 152667

You can do it using boolean indexing with NumPy. For large lists/arrays this can be much faster than a list comprehension or filter approach:

>>> import numpy as np
>>> L1 = [-2, 0.1, 0.75, 4] 
>>> A1 = np.array(L1)           # convert it to an array
>>> A1[(A1 >= -1) & (A1 <= 1)]  # remove all values that are not in the range [-1, 1]
array([ 0.1 ,  0.75])

Upvotes: 12

Tom Wyllie
Tom Wyllie

Reputation: 2085

Seems like the perfect job for filter. (only in python 2!)

L1 = [-2, 0.1, 0.75, 4]
filtered_L1 = list(filter(lambda x: -1. <= x <= 1., L1))
print(filtered_L1)
# [0.1, 0.75]

Python 3 you are better off with a list comprehension;

L1 = [-2, 0.1, 0.75, 4]
L1 = [x for x in L1 if -1. <= x <= 1.]
print(L1)
# [0.1, 0.75]

Upvotes: 0

Sason Torosean
Sason Torosean

Reputation: 572

Here is another.

L2 = [ii for ii in L1 if (ii <= 1 and ii >= -1)]

Upvotes: 0

Oleksii Filonenko
Oleksii Filonenko

Reputation: 1653

Use filter.

L2 = list(filter(lambda x: -1 <= x <= 1, L1))

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

Just use list comprehension:

L2 = [ x for x in L1 if -1 <= x <= 1 ]

Upvotes: 4

Related Questions