assignment with [:]

James Stroud jstroud at mbi.ucla.edu
Sun Dec 28 05:53:35 EST 2008


Ben Bush wrote:
> On Dec 26, 4:46 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
>>> What does *not* work is
>>>         3 * [0,1,2]
>>> As you know, this gives
>>>         [0,1,2,0,1,2,0,1,2]
>>> What I am hoping for is
>>>         [0,3,6]
>>> I see that I can use
>>>         numpy.multiply(3,range(3))
>>> but this seems overkill to me.  Can you tell I am coming to Python from
>>> Matlab?
>> The common way to do this is just
>>
>>   a1 = [0,1,2]
>>   a2 = [x * 3 for x in a1]
>>
>> or, if you need a1 to be done in place:
>>
>>   a1[:] = [x*3 for x in a1]

There is some subtlety here. The latter says to empty the list assigned 
to the name "a1" and refill it with the products. Other references to 
the same list will now reflect this operation. This procedure is not 
equivalent to reassigning the name "a1". For example:

py> a = [1, 2, 3]
py> a1 = a
py> a1[:] = [x*3 for x in a1]
py> a1
     [3, 6, 9]
py> a1
     [3, 6, 9]

Whereas:

py> a = [1, 2, 3]
py> a1 = a
py> a1
     [1, 2, 3]
py> a1 = [x*3 for x in a1]
py> a1
     [3, 6, 9]
py> a
     [1, 2, 3]

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

http://www.jamesstroud.com



More information about the Python-list mailing list