Skip to content
Advertisement

Need to understand how list append() method works with multidimensional list

If I want to make a multidimensional list in python (5×5 list for example), this is the correct code for it (the O is just a sample placeholder for anything):

2dlist = []
for x in range(0,5):
  2dlist.append(['O'] * 5)

However, what exactly does the [‘O’] * 5 mean here? Because, looking at this, I would assume that the list turns out like this for the first iteration of the loop:

[['O'], ['O'], ['O'], ['O'], ['O']]

In reality the list would turn out like this in the first iteration of the loop (which is correct):

[['O', 'O', 'O', 'O', 'O']]

Why?

Advertisement

Answer

Multplying a list by an int multiplies the contents of the list by said int. For example:

a = [1,2] * 3
print(a)

>>> [1,2,1,2,1,2]

This is why in your example when you append ['O'] * 5 to the list you are appending ['O', 'O', 'O', 'O', 'O'] to 2dlist.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement