For loop not updating the list

Main code:

for i in Pool:
    print(i)
    while(i[0] != 1):
        print('i is ' + str(i))
        i=rotate(i) 
        print('after rotate i is ' + str(i)) 
print(Pool)

Rotate Function:

def rotate(a):
    a= a[1:]+a[:1]
    return a

Result:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
i is [2, 1, 3]
after rotate i is [1, 3, 2]
[2, 3, 1]
i is [2, 3, 1]
after rotate i is [3, 1, 2]
i is [3, 1, 2]
after rotate i is [1, 2, 3]
[3, 1, 2]
i is [3, 1, 2]
after rotate i is [1, 2, 3]
[3, 2, 1]
i is [3, 2, 1]
after rotate i is [2, 1, 3]
i is [2, 1, 3]
after rotate i is [1, 3, 2]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

From this code, Pool = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

I can see my rotate function works and rotates 3,2,1 to 2,1,3 but it is not updated to the pool. The result I want is [[1, 2, 3], [1, 3, 2], [1, 3, 2], [1, 2, 3], [1, 2, 3], [1, 3, 2]]

Answer

You’re creating a new list, rather than rotating it in place.

To rotate a list in place, use a[:] = a[1:] + a[:1]; you can then also omit the return (and it’s probably better style to omit it).

def rotate(a):
    """ Rotate the list in-place """
    a[:] = a[1:] + a[:1]

You then call this function without using the return value (which will be None):

for i in Pool:
    while i[0] != 1:
        rotate(i) 

Leave a Reply

Your email address will not be published. Required fields are marked *