python - List comprehension assignment/comparison fails after 256 -


this question has answer here:

i tried find performance difference between slice assignment , regular assignment lists. here code:

import time  n =  1000   = list(range(n)) b = list(range(n))  time1 = time.time() in range(n):     = [x x in if x not i] time2 = time.time() in range(n):     b[:] = [x x in b if x not i] time3 = time.time()  print print b     print time2 - time1 print time3 - time2 

my expectation that, each list a , b, remove 1 element @ time, print a , print b both print empty lists. instead, seem print starting lists, first 256 elements missing.

they both print:

[257, 258, 259 ... n-1] 

what happening?

i'm using python 2.7.6.

the problem you're using is instead of ==.

the former checks object identity, not equality. there's no reason believe evaluating, say, 300+1 twice give same int object, they'll both give int objects value 301.

this happens "work" numbers 256 because particular python implementation* happens intern integers 256. @ startup, creates singleton object number 1, singleton object 2, , on. time expression evaluates number 1, gives object, instead of new one.**

needless say, should not rely on optimization.


* iirc, every version of cpython 1.x days 3.5 defaults behavior integers -5 256, can change limits, or turn off feature, @ build time, , different implementation might different.

** if you're wondering how works in cpython, @ c api level, pylong_fromlong looking numbers -5 256 in array of singleton values. can see 3.4 version of code, example, here; macro check_small_int , actual function get_small_int calls, , static array function uses, in same file, near top.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -