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

Tim Peters tim.one at home.com
Wed Jan 16 00:52:31 EST 2002


[Roy Smith]
> All of the following seem to have the same effect:
>
> x, y = list
> (x, y) = list
> [x, y] = list

They're identical in recent versions of Python.  In early versions, a
distinction was made between tuple unpacking and list unpacking, and if you
really did have a list to unpack only the third way would work.  In Python
2.2, the right-hand side can be any iterable object.  My favorite ridiculous
example is

x, y = file('somefile')

That succeeds only if 'somefile' is a file that exists, is readable, and
contains exactly two lines <wink/sheesh>.

> Is there any reason to prefer one over the other?  FWIW, I tend to write
> the last because I think it looks cleaner.

You can safely suit yourself here; almost all other peoples' code uses the
first form, or rarely the second form in the rare case a multiple-target
assignment spills over multiple lines); I haven't seen the third form in new
code for years.





More information about the Python-list mailing list