Home > Software design >  Why two different value of list is printing when the value of list is not changed?
Why two different value of list is printing when the value of list is not changed?

Time:12-13

In the following Python code value of lis is not changed, then why it is printing two different values?

lis = [[]]
x = lis[0]
print(lis)
x.append(1)
print(lis)

output:

[[]]
[[1]]

CodePudding user response:

Because in python when you assign to var a list from another var, you won't get it's value directly. You only get a link to its address. To get a list from lis directly you need to write:

lis = [[]]
x = lis[0].copy()

This will create a new list for x and empty list would not change.

CodePudding user response:

As lis[0] and x are referenced to the same memory location, changes in x are causing changes in lis.

Instead use:

lis = [[]]
x = lis[0].copy()
print(lis)
x.append(1)
print(x)
  • Related