/  Technology   /  List of lists changes reflected across sublists unexpectedly

List of lists changes reflected across sublists unexpectedly

List of lists changes reflected across sublists unexpectedly

 

Before we dive into the solution, let’s try to understand the question. 

We have a list of lists named p which has the following elements in it 

Now we multiply this list into two using the * operator to form two sublists like in the code shown below.

After this modification, we get a list of lists. Now, if we try to change any one particular element in one of the sublists, the change is seen in the others too.

 

Why is this happening in the first place?

The * operator simply operates with objects. It just creates references, all pointing to the same object. It doesn’t specifically make a copy or separately evaluate each one of them.

The * operator in this example is just trying to make new references of the existing sublists rather than creating new ones.

 

How do we prevent this?

By using list comprehension along with the range() function.

In this approach, the element gets re-evaluated in every iteration. For every evaluation of this element here [2]*4, it creates a new sublist. 

So the change made is reflected not on all sublists but on only one of them.

Note: To learn more about list comprehension refer to the article below.

https://www.i2tutorials.com/list-comprehensions/

Leave a comment