1

I am trying to get rid of unwanted variables in a list. I need to have two condition: one is if making sure the values in my array are smaller than a variable A, and the other is making sure they are not equal to another variable B.

This code dose not work:

original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
new_Ar = [s for s in original_Ar if (s != 2) or (s < 10)]

print (new_Ar)

while if I split it into two statements (instead of the or statement) - they do work:

original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
print ([s for s in original_Ar if (s != 2)])
print ([s for s in original_Ar if (s < 10)])

Any idea how can I do that in one line?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Yair
  • 859
  • 2
  • 12
  • 27

1 Answers1

6

You have your boolean logic mixed up. You want to include all values that are not equal to 2 and are smaller than 10:

new_Ar = [s for s in original_Ar if s != 2 and s < 10]
#           *both* conditions must be true ^^^

Otherwise, you'd include s = 2, because it is smaller than ten, and you'd include s = 11 and s = 12, because both are not equal to two!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343