A Faster Way...

Andrew Dalke dalke at dalkescientific.com
Tue May 10 13:36:25 EDT 2005


andrea.gavana wrote:
> If I simplify the problem, suppose I have 2 lists like:
> 
> a = range(10)
> b = range(20,30)
> 
> What I would like to have, is a "union" of the 2 list in a single tuple. In
> other words (Python words...):
> 
> c = (0, 20, 1, 21, 2, 22, 3, 23, 4, 24, 5, 25, .....

The 'yield' statement is very useful for this sort of thing as
well as the itertools module.  I thought the latter had something
for this already but I don't see it.  Here's an implementation

>>> import itertools
>>> def round_robin(*iterables):
...   iterables = map(iter, iterables)
...   for element in itertools.cycle(iterables):
...     yield element.next()
... 
>>> tuple(round_robin(range(10), range(20, 30)))
(0, 20, 1, 21, 2, 22, 3, 23, 4, 24, 5, 25, 6, 26, 7, 27, 8, 28, 9, 29)
>>> 

Don't know about the speed though.  Didn't have anything to
compare it took.  You mentioned you do a lot of string concatenation
Double checking; do you know that in Python it's faster to append
the new string elements to a list and only then do a single
string concatenation of the list elements?

That is, do

terms = []
for x in data:
   s = process_the_element(x)
   terms.append(s)

s = "".join(data)

rather than

# this is slow if there are many string concatenations
s = ""
for x in data:
  s = s + process_the_element(x)

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list