Possible Duplicate:
A Transpose/Unzip Function in Python
I have a list of sequences, each sequence has two items. I would like to turn this into two lists.
catalog = [('abc', '123'), ('foo', '456'), ('bar', '789'), ('test', '1337')]
Right now I’m just doing this:
names = []
vals = []
for product in catalog:
names.append(product[0])
vals.append(product[1])
print (names)
print (vals)
Which outputs two lists, and works just fine:
['abc', 'foo', 'bar', 'test']
['123', '456', '789', '1337']
Is there a neater, more ‘pythonic’ way of doing this? Or should I stick with what I have? Any corrections or feedback on programming style is welcome, I’m new and trying to learn best practices.
The
*catalogsyntax here is called Unpacking Argument Lists, andzip(*catalog)translates into the callzip(catalog[0], catalog[1], catalog[2], ...).The
zip()builtin function groups iterables by indices, so when you pass a bunch of two-element tuples as above, you get a two-element list of tuples where the first tuple contains the first element of each tuple fromcatalog, and the second tuple contains the second element from each tuple fromcatalog.In a quick timeit test the
zip()version outperforms a looping approach when I tested with 1,000,000 pairs: