Home > OS >  How to reorder a list composed of lists
How to reorder a list composed of lists

Time:03-02

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:

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

CodePudding user response:

In your for loop, you are adding the same list again and again, but instead, you should 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]]
  • Related