Tim
Tim

Reputation: 1

Why do these two lists become the same (python)?

Python query. why does req1 end up being the same as req2? How do I preserve req1 with 3 original values? I would have thought req1 would still be [23,24,25] the following code displays [[23, 24, 25, 26], [23, 24, 25, 26]] ``

req1 = [23,24,25]
req2 = req1
req2.append(26)
op = [[],[]]
op[0] = req2
op[1] = req1
print(op)

``

Upvotes: -3

Views: 36

Answers (1)

Lucas Sander
Lucas Sander

Reputation: 1

req2 = req1

creates a reference to the same object. So when you modify either one, the other what is modifed as well.

Use the copy method to copy all values from on list to a new object.

req2 = req1.copy()

Upvotes: 0

Related Questions