Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get element range in list and swap

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading