I tried to find the performance difference between slice assignment and regular assignment for lists. Here is the code:
import time
N = 1000
a = list(range(N))
b = list(range(N))
time1 = time.time()
for i in range(N):
a = [x for x in a if x is not i]
time2 = time.time()
for i in range(N):
b[:] = [x for x in b if x is not i]
time3 = time.time()
print a
print b
print time2 - time1
print time3 - time2
My expectation is that, for each list a
and b
, this will remove one element at a time, so that print a
and print b
both print empty lists. Instead, they seem to always print the starting lists, but with the first 256
elements missing.
They both print:
[257, 258, 259 ... N-1]
What is happening?
I'm using Python 2.7.6.