Can I join lists with sum()?
<p>Is it pythonic to use <code>sum()</code> for list concatenation?</p>

<pre><code>&gt;&gt;&gt; sum(([n]*n for n in range(1,5)),[])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>

<p>No it's not, Actually it's <a href="http://en.wikichip.org/wiki/schlemiel_the_painter%27s_algorithm" rel="nofollow">shlemiel the painter algorithm</a>. Because each time it wants to concatenate a new list it has to traverse the whole list from beginning. (For more info read this article by Joel:
 <a href="http://www.joelonsoftware.com/articles/fog0000000319.html" rel="nofollow">http://www.joelonsoftware.com/articles/fog0000000319.html</a>)</p>

<p>The most pythonic way is using a list comprehension:</p>

<pre><code>In [28]: [t for n in range(1,5) for t in [n]*n ]
Out[28]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>

<p>Or <code>itertools.chain</code>:</p>

<pre><code>In [29]: from itertools import chain

In [32]: list(chain.from_iterable([n]*n for n in range(1,5)))
Out[32]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>

<p>Or as a pute generator based approach you can use <code>repeat</code> instead of multiplying the list:</p>

<pre><code>In [33]: from itertools import chain, repeat

# In python2.X use xrange instead of range
In [35]: list(chain.from_iterable(repeat(n, n) for n in range(1,5)))
Out[35]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>

<p>Or if you are interest to numpy, or want a super fast approach here is one:</p>

<pre><code>In [46]: import numpy as np
In [46]: np.repeat(np.arange(1, 5), np.arange(1, 5))
Out[46]: array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
</code></pre>

python