Search code examples
pythonlistswitching

How to change numbers around in a list in python


I have a list [50,30,20,10,40] and I am trying to exchange the variables. So what I want to do is if the first number is greater than the next, we have have to flip them. So this should return [30,20,10,40,50]

The code I have so far is given the l as the list

a=''
b=''
c=''
for i in range(len(l)):
    if (l[i+1]<l[i]):
        a=l[i]
        b=l[i+1]
        c=a
        a=b
        b=c
        print [a,b,c]
    else:
        print listOrig

Solution

  • Python makes swapping easy:

    for i in range(len(l)-1):
        if (l[i+1] < l[i]):
            l[i+1], l[i] = l[i], l[i+1]
    

    Notes:

    • for loop goes up to range(len(i) - 1), otherwise your index will be out of range
    • Avoid using single letter variable such as l. In my opinion, loop variable i is OK