How to rearrange a list and set even indexed values to be smaller than odd indexed values in Python

1 Answer

0 votes
def RelstangeOddEven(lst) :
    i = 0
    while (i < len(lst) - 1) :
        if (i % 2 == 0 and lst[i] > lst[i + 1]) :
            lst[i], lst[i + 1] = lst[i+ 1], lst[i]
        if (i % 2 != 0 and lst[i] < lst[i + 1]) :
            lst[i], lst[i + 1] = lst[i+ 1], lst[i]
        i += 1

lst = [1, 2, 3, 5, 8, 6, 7, 4]

RelstangeOddEven(lst)

print(lst)
 


 
 
'''
run:

[1, 3, 2, 8, 5, 7, 4, 6]

'''

 



answered Nov 14, 2022 by avibootz
...