0

In python, the code

x = 0
y = x
y = 1
print x

returns "0" while the code

x = [0]
y = x
y[0] = 1
print x

returns "[1]". Why does python treat lists so differently from integers and what can I do to force it to treat the bottom "x" as it does the top "x"? It seems like the '='s in the respective second lines mean different things - the top one only affects y while the bottom somehow binds x to y. So maybe I need to use a different symbol in the bottom code?

Tim kinsella
  • 113
  • 6

1 Answers1

1
a = [20, 21]
b = [20, 21]

print(a is b) # False
print(a == b) # True
print(id(a) != id(b)) # True

a and b have the same value, but do not refer to the same object.

x = [1]
y = x

print(x is y) # True
print(x == y) # True
print(id(x) == id(y)) # True

x and y have the same value and refer to the same object.

i = [0]
j = i[:] # Copy of i

print(i is j) # False
print(i == j) # True
print(id(i) != id(j)) # True

i and j have the same value, but do not refer to the same object.

srikavineehari
  • 2,502
  • 1
  • 11
  • 21