-1

Hey here i am trying to backup each change of game_list in to game_list_bkp. i was hoping i can append each change that are happening in while loop to game_list_bkp. but if loop runs for 4 times it just append 4 same list to game_list_bkp. i am getting result like [[3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6]] but i need result like[[3], [3, 7], [3, 7, 8], [3, 7, 8, 6]]

import random
val = True
game_list = []
game_list_bkp = []
usr_input = 1
while usr_input <5:
        if usr_input >0:
                game_list.append(random.randint(1,9))
                game_list_bkp.append(game_list)
                print (game_list_bkp)
        if usr_input !=0:
                usr_input = int(input("Enter:"))
        else:
                val=False

Result

[[3]]

Enter:1

[[3, 7], [3, 7]]

Enter:1

[[3, 7, 8], [3, 7, 8], [3, 7, 8]]

Enter:1

[[3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6]]

matisetorm
  • 857
  • 8
  • 21
  • 1
    does not work bc you add a ref to game_list - you need to make a copy of it at the time ( use list.copy() or smth like it) - see https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – Patrick Artner Nov 11 '17 at 11:07

1 Answers1

1

You need to append a copy of game_list every time. You can do it by appending game_list[:] instead of game_list

import random

val = True
game_list = []
game_list_bkp = []
usr_input = 1
while usr_input < 5:
    if usr_input > 0:
        game_list.append(random.randint(1, 9))
        game_list_bkp.append(game_list[:])
        print (game_list_bkp)
    if usr_input != 0:
        usr_input = int(input("Enter:"))
    else:
        val = False
Wodin
  • 3,243
  • 1
  • 26
  • 55