a trick with lists ?
James Turk
james.p.turk at gmail.com
Thu Feb 7 16:19:26 EST 2008
On Feb 7, 12:20 pm, "Sébastien Vincent" <sebastien_nimp73<@>free.fr>
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 ?
if you do
a = [1,2,3]
b = []
b = a
then assign: b[1] = 9
now a[1] == 9 as well
with a[:] = b you are actually getting a copy of the list rather than
an alias
it's hard to say if this is needed in the case you described without
context, but that's what the a[:] = b idiom does
-James
More information about the Python-list
mailing list