[Tutor] Phython List values
Oscar Benjamin
oscar.j.benjamin at gmail.com
Mon Nov 18 12:03:53 CET 2013
On 18 November 2013 06:57, Ayo Rotibi <ayodejirotibi at aol.com> wrote:
> Hi,
Hi, please don't post in HTML.
> I am a complete newbie to python.
>
> I read that an assignment with an = on lists does not make a copy. Instead,
> assignment makes the two variables point to the one list in memory. For
> instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3].
This is correct.
> However, I discovered that if I change the value in ‘a’, ‘b’ does not take
> the new value. I thought since it is pointing to the same storage as ‘a’,
> ‘b’ should take the new value…
It does take the new value. Here is a demonstration:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> a[0] = 'new value'
>>> a
['new value', 2, 3]
>>> b
['new value', 2, 3]
This is because both names a and b are bound to the same list object.
However if you assign a different list object to one of the names then
they will no longer be bound to the same object. Continuing from
above:
>>> a = ['a', 'different', 'list', 'object']
>>> a
['a', 'different', 'list', 'object']
>>> b
['new value', 2, 3]
The key thing is that "bare" assignment (i.e 'a = ...') rebinds the
name a to a new object where as item assignment (i.e. 'a[index]= ...')
changes values in the list that a is bound to.
Oscar
More information about the Tutor
mailing list