[Tutor] A deeper explanation of ability to modify list elements in-place

Richard D. Moores rdmoores at gmail.com
Thu Nov 11 15:56:02 CET 2010


On Thu, Nov 11, 2010 at 06:02, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
> Hi folks,
> I'm trying to gain a deeper understanding of why it's possible to modify
> list elements in-place *without* replacing them. For instance, why is the
> below possible?
>
>>>> class Dummy(object):
> ...     pass
> ...
>>>> a = Dummy()
>>>> b = Dummy()
>>>> x = [a, b]
> # modify list elements in-place
>>>> x[1].name = 'The Dude'
>>>> print x[1].name
> The Dude
>>>> x[0].name = 'The Stranger'
>>>> for item in x:
> ...     print item.name
> ...
> The Stranger
> The Dude
> # modify elements by iterating over the list
>>>> for item in x:
> ...     item.start_date = 2010
>
>>>> for item in x:
> ...     print item.name, item.start_date
> ...
> The Stranger 2010
> The Dude 2010

Would you have the same question about what takes place here?:

>>> list_ = [3,4,5]
>>> list_[1] = 10
>>> list_
[3, 10, 5]
>>>

Dick Moores


More information about the Tutor mailing list