>>> a=range(5)
>>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
[0, 2, 4]
>>> a
[0, 1, 2, 3, 4]
>>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment
SyntaxError: invalid syntax
>>> def setitem(listtochange,n,value): ## function to overcome limitation
listtochange[n]=value
return value
>>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function
['x', 'x', 'x']
>>> a
['x', 1, 'x', 3, 'x'] # We did assignment anyway
>>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
Share
For my timing mentioned (see also the Improving pure Python prime sieve by recurrence formula)
from time import clock
Length function and all with setitem are not satisfactory alternatives, but the timings are here to demonstrate it.
rwh sieve with len function
Length 78498, 257.80008353 ms
rwh sieve with any with side effects
Length 78498, 829.977273648 ms