0

I am studying Python and in the below list called 'picture', I want an output of 0's replaced by space and 1's replace by '*'

picture = [
  [0,0,0,1,0,0,0],
  [0,0,1,1,1,0,0],
  [0,1,1,1,1,1,0],
  [1,1,1,1,1,1,1],
  [0,0,0,1,0,0,0],
  [0,0,0,1,0,0,0]
]
picture_new = picture[:]

###1st answer, trying to practice list
for test in picture:
  for x,y in enumerate(test):
    if y == 0:
      test.pop(x)
      test.insert(x, " ")
    else:
      test.pop(x)
      test.insert(x, "*")
  print("".join(test))

print()
###########################
###2nd answer simplified
for row in picture_new:
  for col in row:
    if(col == 0):
      print(" ", end="")
    else:
      print("*", end="")
  print("")

#why the new picture list is affected by 1st answer...
print(picture)

Both answers, when run individually, give me the exact output that I want which is

   *   
  ***  
 ***** 
*******
   *   
   *

But when I run the whole program, I got the below output. I am wondering why the 2nd list is affected by what I have done with the 1st answer.

   *   
  ***  
 ***** 
*******
   *   
   *   

*******
*******
*******
*******
*******
*******

Please help me in understanding why it seems I am manipulating a single list even though I used two different lists and different variables for for loops.

Thanks and have a great day!

alexisdong
  • 638
  • 7
  • 7
  • 3
    `picture[:]` is a shallow copy - so you copy the **references** inside your list over to another list. Read the dupe, use `other_list = copy.deepcopy(picture)` – Patrick Artner Jun 04 '20 at 19:05
  • 1
    You can also see this by looking at `id(picture), id(picture_new)` (which shows that the two are different), and `[id(row) for row in picture], [id(row) for row in picture_new]` (which shows that the contents of the two are the same) – Randy Jun 04 '20 at 19:12

0 Answers0