How does this code create a grid of 'O's instead of just a single row?


#1
board = []
for i in range(5):
    board.append(['O', 'O', 'O', 'O', 'O'])

I know that it creates 5 lists each of which consists of 5 'O's. How are they ordered in a grid instead of in a single row, because I haven't written any code which puts the 5 lists in new lines.

Also, if you may, explain why using '+=' operator instead of append doesn't work for the same.

board=[]
for i in range(5): 
    board+= ['O', 'O', 'O', 'O', 'O']

#2

Well, let's go through it step by step.

First you are doing,

board = []

This creates an empty list, then

for i in range(5):

This line is a for loop, it loops until the condition is false, then

board.append(['O', 'O', 'O', 'O', 'O'])

This adds to the end of the board object which is a list the list in your append command. It iterates 5 times and each time it appends a list to the list.

board=[]
for i in range(5): 
    board+= ['O', 'O', 'O', 'O', 'O']

This on the other hand adds to the list in a very literal way. After 5 iterations you will have one list of 25 objects instead of one list with 5 lists of 5 objects. A big difference.

Any more questions?