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,fried tasty chicken,old-style boots"
def create_variations(split_string):
init_list = split_string.split(',')
first_element = init_list[0]
# change first element of list to prepare for while loop iterations
popped = init_list.pop()
added = init_list.insert(0, popped)
while init_list[0] != first_element:
popped = init_list.pop()
added = init_list.insert(0, popped)
print init_list # prints as expected, with popped element inserted to index[0] on each iteration
var_list.append(init_list) # keeps appending the same 'init_list' as defined on line 5, not those altered in the loop!
print var_list
create_variations(split_string)
My objective is to create all variations of the init_list
, meaning that the indexes are rotated so that each index gets to be first just once. These variations are then appended to another list, which is the var_list
in this code.
However, I am not getting the result I am expecting from the while loop. In the while loop, the piece of code print init_list
actually prints the variations I want; but the next line of code var_list.append(init_list)
does not append these variations. Instead the init_list
as created on line 5 is repeatedly appended to the var_list
.
What is going on here? And how can I get the different variations of the init_list
created in the while loop to append to the var_list
.
Output I expect for var_list
:
[['fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts', 'blue jeans'],
['blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts'],
['green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins'],
['pink penguins', 'green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots']]