S. Li S. Li -4 years ago 80
Python Question

Issue with list in Python

I'm a noob in Python. I saw this code and I don't quite understand it.

list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1

print(list_1)
print(list_2)

list_1[0] = 'Art'

print(list_1)
print(list_2)


After the program is executed, I know the
list_1
is
['Art', 'Math', 'Physics', 'CompSci']
eventually, but why is the
list_2
also ['Art', 'Math', 'Physics', 'CompSci']. I mean, there's no
list_2 = list_1
after the second
print(list_1)
. Could someone help me out? Thanks!

Update



I tried some new code.

a = 40
b = a
print(a)
print(b)

a = 50
print(a)
print(b)


And the result is

40
40
50
40


So this means, that problem I mentioned before is only for list, right? If I just have a normal variable like
a
and
b
, when I change the value of
a
, the value of
b
won't be affected.

Answer Source

list_2 = list_1 makes list_2 a reference to the exact same list that list_1 references. Throughout this program there's only one list in memory.

This can be verified when printing the memory address:

list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1

print(id(list_1))
# 5430888
print(id(list_2))
# 5430888

You should definitely read this: https://nedbatchelder.com/text/names.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download