a trick with lists ?
bruno.desthuilliers at gmail.com
bruno.desthuilliers at gmail.com
Thu Feb 7 16:37:49 EST 2008
On 7 fév, 22:16, Steve Holden <st... at holdenweb.com> wrote:
> Diez B. Roggisch wrote:
> >> self.tasks[:] = tasks
>
> >> What I do not fully understand is the line "self.tasks[:] = tasks". Why does
> >> the guy who coded this did not write it as "self.tasks = tasks"? What is the
> >> use of the "[:]" trick ?
>
> > It changes the list in-place. If it has been given to other objects, it
> > might require that.
>
> Nowadays it's stylistically better to write
>
> self.tasks = list(tasks)
>
> as it does just the same
Err... not quite, actually.
>>> class Foo(object):
... def __init__(self):
... self.tasks = range(5)
... def test1(self):
... self.tasks[:] = ['a', 'b', 'c']
... def test2(self):
... self.tasks = list(['d', 'e', 'f'])
...
>>> f = Foo()
>>> f.tasks
[0, 1, 2, 3, 4]
>>> alias = f.tasks
>>> alias is f.tasks
True
>>> f.test1()
>>> f.tasks
['a', 'b', 'c']
>>> alias
['a', 'b', 'c']
>>> alias is f.tasks
True
>>> f.test2()
>>> f.tasks
['d', 'e', 'f']
>>> alias
['a', 'b', 'c']
>>> alias is f.tasks
False
>>>
> and makes it a little clearer what's going on
> (though of course if tasks *isn't* a list it won't do *exactly* the same.
>
> regards
> Steve
> --
> Steve Holden +1 571 484 6266 +1 800 494 3119
> Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list