2

I am currently working on a project (In Python 2.7), and ran into a problem when the for values for range() was printed twice. I minimized a lot of the part I am talking about, so if just assume that there are other parts in my code.

So, basically, I have a 5 by 5 board, and depending on case1 and case2, I am copying the board with list() and making alters to it. Then, I want to have a column of numbers stating the row numbers, so that the output will be something like:

1     O O O O O
2     O O O O O
3     O O O O O
4     O O O O O
5     O O O O O

for case1 and case2.

I have:

board = []
# Creating board
for i in range(5):
  board.append(["O"] * 5) 
case1 = True
case2 = True

if case1 == True:
  board1 = list(board) #Making duplicate of board
  # I took out a lot of the code making alterations to board1
  
  for i in range(5):
    board1[i].insert(0, str(i + 1) + "    ")

if case2 == True:
  board2 = list(board) #Making duplicate of board
  # I took out a lot of the code making alterations to board2
  
  for i in range(5):
    board2[i].insert(0, str(i + 1) + "    ")

#Printing the boards
for i in range(5):
  print " ".join(board1[i])

print "\n\n" #Just a gap

for i in range(5):
  print " ".join(board2[i])

However, the output is:

1     1     O O O O O
2     2     O O O O O
3     3     O O O O O
4     4     O O O O O
5     5     O O O O O

for each board1 and board2. I get the expected result when I take out everything concerning case2, however, with my current code, it is printing the range() for the rows printing twice.

I would like to know if there are ways to solve this problem.

Sorry if my wording is very unclear. I would be thankful if somebody to edited the question/title for more clarity.

CEO1111
  • 37
  • 5
  • 5
    `board2 = list(board)` does **not** create a duplicate, its sublists are all still references to the lists from `board`, so anything you do to `board1` or `board2` is affecting all 3 boards. See: https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python If you fix that, do you still have issues? – Random Davis Dec 18 '20 at 17:15

1 Answers1

3

As @Random Davis indicated, the problem comes from the fact that you copy a list of lists, in order to create board1 and board2.

board1=list(board)
board2=list(board)

This way, when you insert the values 1-5 to board1, they will also be inserted in board2, as both are still references to board, therefore when you insert the values in board2, they are inserted for second time.

To avoid this, you must create board1, board2 as below:

board1=[list(i) for i in board]
board2=[list(i) for i in board]

And everything will work properly

Check here why changes to board1 reflect to board2:

Copying nested lists in Python

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

IoaTzimas
  • 10,538
  • 2
  • 13
  • 30