Efficiently Split A List of Tuples

Raymond Hettinger python at rcn.com
Sun Jul 17 22:38:29 EDT 2005


[Richard]
> I know I can use a 'for' loop and create two new lists
> using 'newList1.append(x)', etc.  Is there an efficient way
> to create these two new lists without using a slow for loop?

If trying to optimize before writing and timing code, then at least
validate your assumptions.  In Python, for-loops are blazingly fast.
They are almost never the bottleneck.  Python is not Matlab --
"vectorizing" for-loops only pays-off when a high-speed functional
happens to exactly match you needs (in this case, zip() happens to be a
good fit).

Even when a functional offers a speed-up, much of the gain is likely
due to implementation specific optimizations which allocate result
lists all at once rather than building them one at time.

Also, for all but the most simple inner-loop operations, the for-loop
overhead almost always dominated by the time to execute the operation
itself.

Executive summary:  Python's for-loops are both elegant and fast.  It
is a mistake to habitually avoid them.



Raymond




More information about the Python-list mailing list