Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Appending list to list during while loop - Result not as expected [duplicate]

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']]
like image 731
Darren Haynes Avatar asked Apr 06 '26 07:04

Darren Haynes


1 Answers

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)))
like image 185
Emil Davtyan Avatar answered Apr 08 '26 19:04

Emil Davtyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!