This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author krnick
Recipients docs@python, krnick
Date 2019-10-17.14:45:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1571323511.47.0.548747991495.issue38507@roundup.psfhosted.org>
In-reply-to
Content
When I used the nested list, I need to initialize the nested list, so I used this expression:

>>> nested_list = [[]] * 5

see also: https://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists

So I later learned that such an expression would make the list inside the list have the same reference, which would cause the problem that you modified one element would lead to all elements changed in the nested list.

For example:

>>> nested_list[0].append(1)
>>> nested_list
[[1], [1], [1], [1], [1]]

Therefore, maybe we could tell users how to initialize the list on the documentation like below:

If you need to initialize the nested list, you could follow the below example, also, be aware of the expression like ``[[]] * 5``, this will cause the five lists in the nested list to have the same reference.

   >>> nested_list = [[] for _ in range(5)]
History
Date User Action Args
2019-10-17 14:45:11krnicksetrecipients: + krnick, docs@python
2019-10-17 14:45:11krnicksetmessageid: <1571323511.47.0.548747991495.issue38507@roundup.psfhosted.org>
2019-10-17 14:45:11krnicklinkissue38507 messages
2019-10-17 14:45:11krnickcreate