Personal tools

May 10, 2010

Unchained melody

Collection concatenation can be done in many ways. A fairly underused way is to use the builtin chain method

Let's suppose you have to concatenate several collections objects, e.g.:

>>> a=range(3)
>>> b=set('ale')
>>> c=(a,b)

One easy way to do that is to create an empty list and use the extend method

>>> cat=[]
>>> cat.extend(a)
>>> cat.extend(b)
>>> cat.extend(c)
>>> cat
[0, 1, 2, 'a', 'e', 'l', [0, 1, 2], set(['a', 'e', 'l'])]

But another elegant way do achieve the same result is to use the chain function from itertools

>>> from itertools import chain
>>> chain(a,b,c)

>>> cat=list(chain(a,b,c))
>>> cat
[0, 1, 2, 'a', 'e', 'l', [0, 1, 2], set(['a', 'e', 'l'])]

This is especially useful when you have big amount of data because the result of the chain function is an iterator

Filed under: ,
comments powered by Disqus