Jun 22, 2018

Python list() behaves unexpectedly: Changes reflects to other sub-lists

Image: 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.

Code:
x = 1
mylist = [x]*3

Output:
[1,1,1]

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 [5,5,5].

To fix it, you need to make sure that you create a new list at each position. One way to do it is

[[1]*4 for n in range(3)]

which will reevaluate each [1]*4 , instead of evaluating it once and making 3 references to 1 list.

Dig deeper

* operator cannot make independent objects. Because of the multiplication operator operators on objects by evaluating object references without seeing the expressions.



Leave a Reply :

Captcha

Comments :

Be the first, to comment!