Home > Software engineering >  Get element range in list and swap
Get element range in list and swap

Time:12-31

I want to swap element list by range in python

my code is

List = [1,2,3,4,5,6]

def swap(list_, a, b):
    list_[a], list_[b] = list_[b], list_[a]


swap(List, 0, 5,)
print(List)

and my output is

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

but what i want is swapped by list index range

# my expected output 
n = 2 (add var by input)

#and it swapped to this
[3, 4, 5, 6, 1, 2]

CodePudding user response:

You can use something like this:

def swap(List, n):
    return List[n:]   List[:n]

List = [1,2,3,4,5,6]
n = input()

print(swap(List, n))

Using slice (:) you can split your list in sublists by index. Then you can recombine them in the return statement

  • Related