Better way to swap elements in a list?
<p>I have a bunch of lists that look like this one:</p>

<pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre>

<p>I want to swap elements as follows:</p>

<pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
</code></pre>

<p>The size of the lists may vary, but they will always contain an even number of elements.</p>

<p>I'm fairly new to Python and am currently doing it like this:</p>

<pre><code>l =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
final_l = []
for i in range(0, len(l)/2):
    final_l.append(l[2*i+1])
    final_l.append(l[2*i])
</code></pre>

<p>I know this isn't really <a href="https://en.wiktionary.org/wiki/Pythonic#Adjective">Pythonic</a> and would like to use something more efficient. Maybe a list comprehension?</p>

<p>You can use the <a href="http://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list">pairwise iteration</a> and chaining to <a href="http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python">flatten the list</a>:</p>

<pre><code>&gt;&gt;&gt; from itertools import chain
&gt;&gt;&gt;
&gt;&gt;&gt; list(chain(*zip(l[1::2], l[0::2])))
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
</code></pre>

<p>Or, you can use the <a href="https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable"><code>itertools.chain.from_iterable()</code></a> to avoid the extra unpacking:</p>

<pre><code>&gt;&gt;&gt; list(chain.from_iterable(zip(l[1::2], l[0::2])))
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
</code></pre>

python