Reverse zip() ?

Bryan Olson fakeaddress at nowhere.org
Tue Dec 2 20:55:27 EST 2008


Zac Burns wrote:
> There is a problem with this however, which prompted me to actually
> write an unzip function.
> 
> One might expect to be able to do something like so (pseudocode)...
> 
> def filesAndAttributes():
>    files = walk()
>    attributes = [attr(f) for f in files]
>    return zip(files, attributes)

You could do away with that zip and just let the list comprehension 
return tuples.

     [(f, attr(f)) for f in walker()]

> files, attributes = zip(*filesAndAttributes())
> 
> The corner case is when dealing with empty lists and there aren't
> enough items to unpack.

Can you give a concrete example?

> The unzip function therefore has an elementsForEmpty keyword that
> handles this case. Perhaps something like this could be added to zip?

The built-in zip stops when any of the given iterables stops. The 
itertools module has izip_longest (or zip_longest in Python 3), which 
takes a fillvalue argument. Perhaps that's what you want?


-- 
--Bryan



More information about the Python-list mailing list