Universally unpacking tuples

Alex Martelli aleax at aleax.it
Mon Sep 23 02:39:23 EDT 2002


Peter Bittner wrote:
        ...
> arbitraryTuple = ('abc', '123', 'qwert', ...)
> while len(arbitraryTuple) > 0:
>   elem, arbitraryTuple = arbitraryTuple
>   print elem
> 
> Well, I know this doesn't work since unpacking requires the correct
> number of elements on the left side... :-(
        ...
> mylist = ['abc', '123', 'qwert', ...]
> for i in range(len(mylist)):
>   elem = mylist[i]
>   print elem

The second snippet works just as well whether name mylist refers to
a list, or to a tuple.  Tuples are indexable just like lists are --
they're not _modifiable_, but that's a different issue.

However, the simplest solution of all, also universally applicable
to all sequences (lists, tuples, strings, ...) and other iterables
(directories, files, ...) is:

for elem in whatever:
    print elem


Back to the problem of what you try to accomplish in the first
statement of the first loop above:

elem, whatever = whatever[0], whatever[1:]

this sets elem to the first argument of 'whatever' (can be a
tuple, list, string, ...) and re-binds name 'whatever' to all
elements except the first (keeping the same type as was in use
before -- again, could be tuple, list, string, etc, etc).  You
do not need it here, and it would be a substantial waste of
both programming and computational effort to use it, but in
some other cases it might indeed come in handy.


Alex




More information about the Python-list mailing list