0

When trying to remove a number from a particular list that has xy-coordinates in a list-of-lists, python removes that number from (nearly) all lists with different coordinates too. How do I prevent this from happening?

So I'm trying to write a code that can solve Sudokus, but something goes wrong when I run it. The idea is that the code keeps track of which options are still available for every spot. These options are saved in a list-of-lists, with all the sets of options being lists on their own. My code has way too many numbers in it, so I'll use a simplified version here.

options = [1, 2, 3]
board = [[options for c in range(2)] for r in range(2)]
''' which gives the following board: 
[[[1, 2, 3], [1, 2, 3]], 
[[1, 2, 3], [1, 2, 3]]] '''

board[0][0].remove(1)

What I want this code to do (and I thought it should) is to remove the option '1' only from the options at (0, 0), but it removes '1' from the options at all coordinates. How can I have the code do what I want it to?

  • Python FAQ: [How do I create a multidimensional list?](https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list) – Matthias Oct 26 '19 at 10:40

1 Answers1

1

See below (Your code points to the one and only copy of options. The code below clone the options)

import copy

options = [1, 2, 3]
board = [[copy.deepcopy(options) for c in range(2)] for r in range(2)]

board[0][0].remove(1)
balderman
  • 22,927
  • 7
  • 34
  • 52
  • In this case a simple copy would be enough: `board = [[options[:] for c in range(2)] for r in range(2)]` but as the OP said that the example was simplified `deepcopy` is the way to go. – Matthias Oct 26 '19 at 10:44
  • That really helps! Thanks! Of course you can also make it with `[[[i+1 for i in range(3)] for k in range(2)] for r in range(2)]` which also solves the problem. – Gijs Drost Oct 26 '19 at 14:20
  • I am glad it helps. Feel free to voteup. – balderman Oct 26 '19 at 16:06