a trick with lists ?

Steve Holden steve at holdenweb.com
Thu Feb 7 23:52:49 CET 2008


Tim Chase 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 and makes it a little clearer what's going on 
> 
> Um...except it's not "just the same"?
> 
>    class Foo(object):
>      def __init__(self, tasks):
>        self.tasks1 = tasks
>        self.todo1 = [self.tasks1, 42]
>        self.tasks2 = tasks
>        self.todo2 = [self.tasks2, 42]
>      def new_tasks1(self, tasks):
>        self.tasks1 = list(tasks)
>      def new_tasks2(self, tasks):
>        self.tasks2[:] = list(tasks)
>      def __str__(self):
>        return "%r\n%r" % (self.todo1, self.todo2)
> 
>    f = Foo([1,2,3])
> 
>    f.new_tasks1([4,5,6])
>    print 'task1'
>    print f # todo1/2 haven't been changed
> 
>    print 'task2'
>    f.new_tasks2([4,5,6])
>    print f # both todo 1 & 2 have been changed
> 
> Assignment to a name just rebinds that name.  Assignment to a 
> slice of a list replaces the contents in-place.
> 
[sigh] Right, I got the assignment the wrong way around (and clearly you 
can't put list(tasks) on the left-hand side of an assignment).

Of course

     self.tasks = list(tasks)

is equivalent to

     self.tasks = tasks[:]

Thanks for pointing out my error.

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