0

I'm trying some problems on a coding website, and one of the questions requires users to make an empty nested list of n size. So naturally my first inclination was to just multiply like so:

list = [[0]*n]*n

But this didn't work because the rest of the code went into the list and changed values, and this solution got out of bounds errors. The below code, however, did work.

list = [[0]*n for _ in range (n)]

I'm wondering how this could be. The results in my IDLE are identical as far as I can tell.

Thank you

C Grant
  • 11

1 Answers1

-1

This is a well-known pitfall faced by beginners. When the * operator is used on a list, the object reference is duplicated. No copy of the list is made. You can check it by doing id() on list elements.

The second piece of code creates n lists separately. Hence each one has its own unique object reference.

Update: This is documented on Udacity as the first pitfall: https://www.udacity.com/wiki/common-python-pitfalls

coder.in.me
  • 1,048
  • 9
  • 19