Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap values in python?

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.

like image 415
Winniez Avatar asked Mar 27 '26 19:03

Winniez


1 Answers

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.

like image 78
no_name Avatar answered Mar 29 '26 09:03

no_name