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

How to reorder a list composed of lists

I am trying to tranform

[[1, 2, 3], [1, 2]] 

into

[[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 2], [2, 1]]

But instead of the correct output, I am getting this:

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

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2], [1, 2]]

Here is my code

def listReorder(list1):
List2 = []
for list in list1:
    listTemp = list
    for item in list:
        List2.append(listTemp)
        t=listTemp.pop()
        listTemp.insert(0, t)
return List2

List = [[1, 2, 3], [1, 2]]
listReorder(List)

>Solution :

In python, lists are passed by reference, when you change the list in the loop, it is not adding a copy of that list to the final output, but instead, it is adding its reference. So instead, you can make a copy of the list in the iteration.

def listReorder(list1):
    List2 = []
    for list in list1:
        listTemp = list
        for item in list:
            List2.append([x for x in listTemp])
            t=listTemp.pop()
            listTemp.insert(0, t)
    return List2

List = [[1, 2, 3], [1, 2]]
listReorder(List)

Output:

[[1, 2, 3], [3, 1, 2], [2, 3, 1], [1, 2], [2, 1]]
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