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)
``
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)
``
Share Improve this question edited Feb 4 at 17:50 Tim asked Feb 2 at 15:46 TimTim 11 silver badge6 bronze badges 3- 4 What language are you using? – NickSlash Commented Feb 2 at 15:49
- It's likely a pass-by-reference vs pass-by-value issue regardless of language. – NickSlash Commented Feb 2 at 15:52
- Please edit your question to tag it with the language you are using. – dbc Commented Feb 3 at 16:45
1 Answer
Reset to default 0req2 = 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()