["O"] times 5?


#1

maybe a stupid question but i dont get this:

if i write this code:
table = []
for x in range(5):
table.append([“O”])

the result is a list of 5 lists with a string “O” [[‘O’], [‘O’], [‘O’], [‘O’], [‘O’]]
but when i multiply it 5 times:
table.append([“O”] * 5) shouldnt i get my table list to have 25 [“O”] lists and not 5 lists of [‘O’, ‘O’, ‘O’, ‘O’, ‘O’]??


#2
def board_size(x):
	for i in range(x):
		board.append(["O"] * x)

The for loop is what is creating each row, the append * (x) is what is creating the columns, its just creating a list and extending it.

Each append is a list.

Think of it as a faster way of doing the following

board = []    
for i in range(6): # create a list with nested lists
    board.append([])
    for n in range(6):
        board[i].append("O") # fills nested lists with data

Feel free to play around with other board sizes in the IDE on CA or do some testing over @ https://repl.it


#3

I get the code and what id does. What i don’t get is why does the * not multyply the whole list but just the “O” inside it. When I see the [“O”] * 5, I expect to get [[“O”][“O”][“O”][“O”][“O”]], not [[‘O’, ‘O’, ‘O’, ‘O’, ‘O’]]


#4

['O'] * 5 gives ['O', 'O', 'O', 'O', 'O']

given we multiple a 1d list, the result should also be a 1d list. We can’t just change the dimension of the list by doing a multiplication.

1d = 1 dimensional list.


#5

When you multiply a number you don’t get more numbers, you get a bigger one


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.