Why does the whole column change?


#1


Hey guys! I finished the exercises, but then I took some time to try and create a battleship myself, and...

Instead of getting one 'O' changed on the board, I'm getting the whole column changed into '*'/'X' and I really can't figure why that happens...


list = []
x = ['O'] * 5
for i in range(5):
 list.append(x)
def board(list):
 for row in list:
  print ' '.join(row)
board(list)
import random
def sadas(list):
 return random.randint(0, len(list) - 1)
def asdas(list):
 return random.randint(0, len(list[0]) - 1)
randrow = sadas(list)
randcol = asdas(list)
print randrow, randcol
def ffff():
 inprow = raw_input('Enter row: ')
 inpcol = raw_input('Enter col: ')
 try:
  inprow = int(inprow) - 1
  inpcol = int(inpcol) - 1
 except: 
  print 'Oops! Looks like you didn\'t enter a real number, try again!'
  ffff()
 if inprow < 0 or inprow > 4 or inpcol < 0 or inpcol > 4:
  print 'You entered an invalid number! Try again!'
  ffff()
 if inprow == randrow and inpcol == randcol:
  list[randrow][randcol] = '*'
  board(list)
  print 'Congratulations! You won!'
 else:
  list[inprow][inpcol] = 'X'
  board(list)
ffff()


I can't really figure out where the error is. Please help!
Update: And this is how the output looks like:

O * O O O
O * O O O
O * O O O
O * O O O
O * O O O
Congratulations! You won!

#2

You're referring to the same list five times - values are not copied when you do assignment, it's the reference to the value that is copied.

a = []
b = a
print a is b  # True (not just equal, but same)
a = []
print a is b  # False (equal, but no longer the same)