Skip to content Skip to sidebar Skip to footer

Python - Appending List To List During While Loop - Result Not As Expected

Python/programming newbie here, trying to figure out what is going in with this while loop. First the code: var_list = [] split_string = 'pink penguins,green shirts,blue jeans,frie

Solution 1:

Here some code that does what I think you want in a simpler fashion :

variations = []
items = [1,2,3,4,5]

for i in range(len(items)):
    v = items[i:] + items[:i]
    variations.append(v)

print variations

Output :

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

Or you can use this simple generator :

(items[i:] + items[:i] for i in range(len(items)))

Solution 2:

With this line

var_list.append(init_list)

you are adding a reference to init_list everytime. But you need to create a new list. Use this

var_list.append(init_list[:])

Explanation

When you are printing init_list, it prints the current state. When you are adding it to var_list, you are not adding the current state. You are adding a reference. So, when the actual list changes all references point to the same data.

And you can simplify your program like this

def create_variations(split_string):
    init_list = split_string.split(', ')
    for i in range(len(init_list)):
        var_list.append(init_list[:])
        init_list.insert(0, init_list.pop())

    print var_list

Post a Comment for "Python - Appending List To List During While Loop - Result Not As Expected"