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

Philip Swartzleonard starx at pacbell.net
Tue Jan 15 22:11:19 EST 2002


Andy Todd || Tue 15 Jan 2002 06:10:27p:

> 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. 

I'm not a guru either, but i'm fairly sure that the first one is ALSO 
creating a temporary tuple, (at least as much as the second), as any comma 
seperated statement such as that IS a tuple. If you type '3,4' on the 
command line, you get '(3,4)' spit back at you, and if you say 'x=a,b' x is 
a tuple. AFAIR the only time a tuple NEEDS parens is for the empty one.
 
> Mind you, you may confuse people with options 2 and 3 so its probably
> best to stick with the first one. 

Well, 3 lets you know that the person wants to be working with a list... 
i'd say 2 is right out though.

> 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. 

Of course, we might know it does, but just not care (list of lines in a 
file?) =)
 
> Regards,
> Andy



-- 
Philip Sw "Starweaver" [rasx] :: <nothing>



More information about the Python-list mailing list