How to change numbers in a list in python

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

The code I still gave l as a 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
+4
source share
1 answer

Python simplifies data sharing:

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 the loop goes into the range (len (i) - 1), otherwise your index will be out of range.
  • Avoid using a one-letter variable, for example l. In my opinion, the loop variable iis fine
+3
source

All Articles