Why does this print a list of 5 items instead of 5 distinct lists?


#1


https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/3?curriculum_id=4f89dab3d788890003000096

I correctly solved this exercise.

My question is why does the piece of code below produce the list [O, O, O, O, O] rather than 5 lists like: [O], [O], [O], [O], [O].

When I look at the piece of code, I don't understand why we know that will produce a single list with several entries, rather than reproducing the list of a single entry.

Thanks!


print ["O"] * 5


#2

That would actually be,

["O", "O", "O", "O", "O"]

It likely has to do with assignment. If we write,

a = ['O'], ['O'], ['O'], ['O'], ['O']

it will create a tuple of lists.

    print a    # (['O'], ['O'], ['O'], ['O'], ['O'])

It could be made to work, though. But it's not what is expected here.

From a standpoint of program logic, the behavior exhibited is something we might expect from Python. A list of identical elements.

board = []
for k in range(5):
    board[k] = ["O"] * 5

def print_board(board):
    for k in range(len(board)):
        print " ".join(board[k])

If we attempt to create a tuple, we end up with a string.

y = ("O") * 5
print y       # OOOOO

If we manually create the tuple,

a = ('O','O','O','O','O')
print " ".join(a)         # O O O O O

that would mean our program could not dynamically create any size of board. It would take some thought.


#3

Thanks for the response!