-1

For my assignment, I need to insert a value into a particular index in a sublist of a list which contains 3 lists. Instead of changing the value in only 1 sublist, it changes it in every sublist.

I have tried reentering the values which are used to determine the indices.

def make_move(cur, move, player):
  m0 = move[0]
  m1 = move[1]
  cur[m0][m1] = player
make_move(world, (1,0), 'X')
print(world)

I expect the output to be:

[['', '', ''], ['X', '', ''], ['', '', '']]

What I am receiving is:

[['X', '', ''], ['X', '', ''], ['X', '', '']]

I made the world function as follows:

def set_up_game(size):
  n = 0
  num = 0
  s = int(get_game_size(size))
  game = []
  rows = []
  columns = ''
  while n < s:
    rows.append(columns)
    n += 1
  while num < s:
    game.append(rows)
    num += 1

  return game
JBarnes
  • 11
  • 4
  • 4
    You should show how you made the `world` list. It looks like it contains three references to the same list. – Mark Nov 03 '19 at 01:53
  • Possible duplicate: [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – wwii Nov 03 '19 at 02:10

1 Answers1

0

The problem is the line:

game.append(rows)

Change it to:

game.append(list(rows))

Which will create new lists within the game list.


What you did initially (with the while loop) is equivalent to:

game = [row] * num

You can see the problem with doing that here.

smac89
  • 39,374
  • 15
  • 132
  • 179