Skip to content Skip to sidebar Skip to footer

Excluding Items From A List That Are In A Certain Range Using List Comprehension

I have two lists: a = [10.0,20.0] and b = [1.0,10.0,15.0,20.0,30.0,100.0]. How can I remove from list b all the elements between 10.0 and 20.0? Here is what I tried: c = [b[y] for

Solution 1:

You can simplify by iterating b's elements directly, but your original code works for me, too:

a = [10.0, 20.0]
b = [1.0, 10.0, 15.0, 20.0, 30.0, 100.0]

c = [x for x in b if x < a[0] or x > a[1]]
# [1.0, 30.0, 100.0]# Your version:c = [b[y] for y in range(len(b)) if (b[y] < a[0] or b[y] > a[1])]
# [1.0, 30.0, 100.0]

Solution 2:

Think from the opposite, only includes components that are in a certain range, like this:

c = [y for y in b if (y < a[0] or y > a[1])]

Solution 3:

You can use filter:

a = [10.0,20.0]
b = [1.0,10.0,15.0,20.0,30.0,100.0]
new_a = list(filter(lambda x:x < a[0] or x > a[-1], b))

Output:

[1.0, 30.0, 100.0]

Solution 4:

Filter function will do this for you :

c= filter(lambda x: x<10.0 or x>20.0,b)

Post a Comment for "Excluding Items From A List That Are In A Certain Range Using List Comprehension"