0
def random_row(board, length):
    return randint(0, len(board) - length)


def random_col(board, length):
    return randint(0, len(board[0]) - length)

ship_all = []

for length in range(1,6):
    ship = []
    ship_row = random_row(board, length)
    ship.append(ship_row)
    ship_col = random_col(board, length)
    ship.append(ship_col)
    i = 0
    if randint(0,1) == 0:
        while i<length:
            ship_all.append(ship)
            ship[0] += 1
            print ship
            i+=1
    else:
        while i<length:
            ship_all.append(ship)
            ship[1] += 1
            print ship
            i+=1

print ship_all

The ship_all.append(ship) just give the final result of the ship, but print ship works out correctly, how to solve this problem?

Liye
  • 3
  • 4
  • Because you're filling `ship_all` with *multiple references to the same list*. Move `ship = []` *inside* the `while` loops. – jonrsharpe Feb 27 '15 at 12:07

1 Answers1

2

You are not adding copies of ship to ship_all, you are adding the same list object over and over again, altering that object each iteration.

Create a copy of the list each time you append:

ship_all.append(ship[:])

or create the ship list from scratch inside the while loops.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343