I know how to swap two variables together but I want to know if there is a quicker way to follow a certain pattern.
So I have this list of number. list=[1,2,3,4,5,6]
And what I want to do is to swap a number with the following one and swap the next number with the number after it. so after swapping them it would become list=[2,1,4,3,6,3]
So I was wondering if there was a way to be able to swap the numbers more simply. Thank you.
lst = [1,2,3,4,5,6] # As an example
for x in range(0, len(lst), 2):
if x+1 == len(lst): # A fix for lists which have an odd-length
break
lst[x], lst[x+1] = lst[x+1], lst[x]
This doesn't create a new list.
Edit: Tested and it's even faster than a list comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With