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>An(other) alternative:</p>

<pre><code>final_l = list() # make an empty list
for i in range(len(l)): # for as many items there are in the original list
    if i % 2 == 0: # if the item is even
        final_l.append(l[i+1]) # make this item in the new list equal to the next in the original list
    else: # else, so when the item is uneven
        final_l.append(l[i-1]) # make this item in the new list equal to the previous in the original list
</code></pre>

<p>This assumes that the original list has an even number of items. If not, a <a href="https://docs.python.org/3.4/tutorial/errors.html" rel="nofollow">try-except</a> can be added:</p>

<pre><code>final_l = list()
for i in range(len(l)):
    if i % 2 == 0:
        try: # try if we can add the next item
            final_l.append(l[i+1])
        except:  # if we can't (because i+1 doesnt exist), add the current item
            final_l.append(l[i])
    else:
            final_l.append(l[i-1])
</code></pre>

python