-1

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]]
S.B
  • 13,077
  • 10
  • 22
  • 49

2 Answers2

0

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.

Даниял
  • 151
  • 1
  • 6
0

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)
Kedar U Shet
  • 538
  • 2
  • 11