EliseB EliseB - 3 months ago 13
Python Question

Better way to swap elements in list?

I have a bunch of lists that look like this one:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


I want to swap elements as follows:

final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]


The size of the lists may vary but they will always contain an even number of elements.

I'm fairly new to python and am currently doing it like this:

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])


I know this isn't really 'pythonic' and would like to use something more efficient.
Maybe a list comprehension?

Answer

No need for complicated logic, simply rearrange the list with slicing and step:

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

In [2]: l[::2], l[1::2] = l[1::2], l[::2]

In [3]: l
Out[3]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
Comments