1

I'd like to fill a list with numbers from 0 to 999, except a certain number. But it looks like the certain number can be from 0 to 256 only; if it's anything over 257 or greater, "if i is not ..." part is ignored. Would someone explain why this is so in Python (both 2.x and 3.x)?

>>> l = [i for i in range(1000) if i is not 255]; len(l)
999
>>> l = [i for i in range(1000) if i is not 256]; len(l)
999
>>> l = [i for i in range(1000) if i is not 257]; len(l)
1000
>>> l = [i for i in range(1000) if i is not 258]; len(l)
1000
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
  • This would be a better duplicate: http://stackoverflow.com/questions/306313/pythons-is-operator-behaves-unexpectedly-with-integers – Jeff Mercado May 29 '15 at 01:55

2 Answers2

3

is tests whether two values are the same value, not whether they're equal. Python uses "singleton" values for small integers, but larger integers are a new object every time.

Don't use is for anything other than None, unless you are absolutely sure what you're doing. Use ==/!=.

I wrote about this once.

Eevee
  • 47,412
  • 11
  • 95
  • 127
1

Test equality with == rather than is and inequality with != instead of is not.

>>> l = [i for i in range(1000) if i is not 257]; len(l)
1000
>>> l = [i for i in range(1000) if i != 257]; len(l)
999
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97