a trick with lists ?

Helmut Jarausch jarausch at igpm.rwth-aachen.de
Fri Feb 8 04:40:29 EST 2008


Sébastien Vincent <sebastien_nimp73 wrote:
> I've found some class on the Net which takes basically this form :
> 
> ######
> class Foo:
>     def __init__(self):
>         self.tasks = []
>    ...
> 
>     def method1(self):
>         tasks = []
>         while True:
>   ...
>   append/pop elements into/from tasks
>   ...
>   if condition : break
> 
>     self.tasks[:] = tasks
>         return
> ######
> 
> 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 ?
> 

I've just run into this difference myself.
As several others have pointed out, assignment to
self.task[:] modifies this list in place.

Here my example showing a striking difference

class MyClass(object) :
   def shorten_list(self,outer_list) :
     ll=len(outer_list)
     if  ll > 0 :
       outer_list[:]= outer_list[:ll-1]


mylist=[1,2,3]
MyClass().shorten_list(mylist)
print mylist

// this prints  [1, 2]   (as expected)

class MyClass2(object) :
   def shorten_list(self,outer_list) :
     ll=len(outer_list)
     if  ll > 0 :
       outer_list= outer_list[:ll-1]


mylist=[1,2,3]
MyClass2().shorten_list(mylist)
print mylist

# this prints  [1, 2, 3]

The shortened list outer_list[:ll-1] has been assigned (bound in Python terms)
to the LOCAL reference (to a list) 'outer_list'

-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany



More information about the Python-list mailing list