unpacking lists (there's more than one way to do it!)

Andy Todd andy47 at halfcooked.com
Tue Jan 15 21:10:27 EST 2002


Roy Smith <roy at panix.com> wrote in
news:roy-1049EA.20421115012002 at news1.panix.com: 

> All of the following seem to have the same effect:
> 
> x, y = list
> (x, y) = list
> [x, y] = list
> 
> Is there any reason to prefer one over the other?  FWIW, I tend to
> write the last because I think it looks cleaner.

Whilst I'm no guru, you should probably be using the first. Mind you,
they all have the same *end* result. 

With your second and third options you are temporarily creating a tuple
and  a list which are unnamed and so inaccessible in the local namespace
but which contain two new local variables (x and y) that are named and
hence accessible. The net effect will be a little extra memory used
(which should be garbage collected very quickly) and therefore negligible
to all but the most keen observer. 

Mind you, you may confuse people with options 2 and 3 so its probably
best to stick with the first one. 

Of course, another question is what happens if list ever has more than
two items in it, but we will leave that for another day. 

Regards,
Andy
-- 
Contents free posts a speciality



More information about the Python-list mailing list