Python list() behaves unexpectedly: Changes reflects to other sub-lists
Lists … are the inbuilt data structure of Python programming language. Usually defines using ,list(data) etc.
Now, before going to our problem lets see some codes and their output to effectively understand the problem.
x = 1
mylist = [x]*3
Explanation of the Code:
When you write
[x]*3, you essentially, the list
[x, x, x]. The
mylist doesn’t contain the list with 3 copy of x. Instead of
mylist with 3 references to the same x. Let’s assume we change the value of x to 5 in the next line then all values of
mylist will change to 5, the list will look like
To fix it, you need to make sure that you create a new list at each position. One way to do it is
[*4 for n in range(3)]
which will reevaluate each
*4 , instead of evaluating it once and making 3 references to 1 list.
* operator cannot make independent objects. Because of the multiplication operator operators on objects by evaluating object references without seeing the expressions.