4

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
1
  • Are you trying to sort it? Nov 29, 2014 at 5:38

1 Answer 1

3

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.