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>Here a single list comprehension that does the trick:</p>

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

In [2]: [l[i^1] for i in range(len(l))]
Out[2]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
</code></pre>

<p>The key to understanding it is the following demonstration of how it permutes the list indices:</p>

<pre><code>In [3]: [i^1 for i in range(10)]
Out[3]: [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
</code></pre>

<p>The <code>^</code> is the <a href="https://en.wikipedia.org/wiki/Exclusive_or">exclusive or</a> operator. All that <code>i^1</code> does is flip the least-significant bit of <code>i</code>, effectively swapping 0 with 1, 2 with 3 and so on.</p>

python