views:

184

answers:

4
>>> 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
+24  A: 

Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead:

for i in range(0,len(a),2):
    a[i] = 3

Apart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and completely unnecessary here.

Mark Byers
I wish I could upvote this more than once. And don't call your function `set`.
Tim Pietzcker
Have to say that it did not come to me even after your comment that yes there is set in Python even not function like in Lisp.
Tony Veijalainen
As for side effects, I know they are not always appreciated, but sometimes very useful. I think this code for example is a beauty: Solve Every Sudoku Puzzle http://norvig.com/sudoku.html If the value is not used, the intention is quite clear.
Tony Veijalainen
+8  A: 

Yes. And I recommend using

a[::2] = ['x'] * len(a[::2])

instead.


Edit:

Microbenchmarks for Python 2.6:

~:249$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * len(a[::2])'
10000 loops, best of 3: 26.2 usec per loop

~:250$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * (len(a)/2)'
10000 loops, best of 3: 19.6 usec per loop

~:251$ python2.6 -m timeit -s 'a = range(2000)' 'for i in xrange(0,len(a),2): a[i] = 8'
10000 loops, best of 3: 92.1 usec per loop

~:252$ python2.6 -m timeit -s 'a = range(2000)
> def assign(x,i,v):x[i]=v;return v' '[assign(a,i,8) for i in xrange(0, len(a), 2)]'
1000 loops, best of 3: 336 usec per loop

Python 3.1:

~:253$ python3.1 -m timeit -s 'a = list(range(2000))' 'a[::2] = [8] * len(a[::2])'
100000 loops, best of 3: 19.8 usec per loop

~:254$ python3.1 -m timeit -s 'a = list(range(2000))' 'a[::2] = [8] * (len(a)//2)'
100000 loops, best of 3: 13.4 usec per loop

~:255$ python3.1 -m timeit -s 'a = list(range(2000))' 'for i in range(0,len(a),2): a[i] = 8'
10000 loops, best of 3: 119 usec per loop

~:256$ python3.1 -m timeit -s 'a = list(range(2000))
> def assign(x,i,v):x[i]=v;return v' '[assign(a,i,8) for i in range(0, len(a), 2)]'
1000 loops, best of 3: 361 usec per loop
KennyTM
See my other post on sieve optimization that regeneration and len are too expensive. I can give you timing results if you want by simple time.clock() timing.
Tony Veijalainen
+1  A: 

You can also use list.__setitem__

a = range(5)
[a.__setitem__(i,"x") for i in range(0,len(a),2)]

Or if you want to avoid the contruction of an intermediate list:

any(a.__setitem__(i,"x") for i in range(0,len(a),2))

But assignment in list comprehensions is indeed unpythonic.

gilesc
Thanks for data, I corrected the function name in my question to correspond to this private function name.
Tony Veijalainen
Well, your edit sort of misses the point --- list.__setitem__ is a builtin function, meaning you don't have to define it yourself; it's automatically included in all lists.
gilesc
See post below for time comparison, not so good unfortunately. I needed to take out that set as name as it is built in and as __setitem__ is private it is OK to use 'setitem' only.
Tony Veijalainen
A: 

For my timing mentioned (see also the http://stackoverflow.com/questions/3285443/improving-pure-python-prime-sieve-by-recurrence-formula) from time import clock

def rwh_primes1(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

def rwh_primes_tjv(n):
    # recurrence formula for length by amount1 and amount2 tjv
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    amount1 = n-10
    amount2 = 6

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
             ## can you make recurrence formula for whole reciprocal?
            sieve[i*i//2::i] = [False] * (amount1//amount2+1)
        amount1-=4*i+4
        amount2+=4

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_len(n):
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * len(sieve[i*i//2::i])

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_any(n):
    """ Returns  a list of primes < n """
    halfn=n//2
    sieve = [True] * (halfn)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            any(sieve.__setitem__(item,False) for item in range(i*i//2,halfn,i))

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]


if __name__ == "__main__":
    n = 1000000

    print("rwh sieve1")
    t=clock()
    r=rwh_primes1(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with recurrence formula")
    t=clock()
    r=rwh_primes_tjv(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with len function")
    t=clock()
    r=rwh_primes_len(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with any with side effects")
    t=clock()
    r=rwh_primes_any(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))
    raw_input('Ready')

""" Output:
rwh sieve1
Length 78498,  213.199442946 ms
rwh sieve with recurrence formula
Length 78498,  218.34143725 ms
rwh sieve with len function
Length 78498,  257.80008353 ms
rwh sieve with any with side effects
Length 78498,  829.977273648 ms
Ready
"""

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

Tony Veijalainen