classification
Title: Improve the documentation of the nested list initialization
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.8
process
Status: closed Resolution: duplicate
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, krnick, serhiy.storchaka
Priority: normal Keywords:

Created on 2019-10-17 14:45 by krnick, last changed 2019-10-17 15:42 by krnick. This issue is now closed.

Messages (3)
msg354844 - (view) Author: JUN-WEI SONG (krnick) * Date: 2019-10-17 14:45
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)]
msg354848 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2019-10-17 15:31
It is already documented. See note 2 at https://docs.python.org/3/library/stdtypes.html#common-sequence-operations.
msg354849 - (view) Author: JUN-WEI SONG (krnick) * Date: 2019-10-17 15:42
sorry that I did not notice it already documented
History
Date User Action Args
2019-10-17 15:42:20krnicksetstatus: open -> closed
resolution: duplicate
messages: + msg354849

stage: resolved
2019-10-17 15:31:01serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg354848
2019-10-17 14:45:11krnickcreate