admin管理员组文章数量:1307584
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()
本文标签: Why do these two lists become the same (python)Stack Overflow
版权声明:本文标题:Why do these two lists become the same (python)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741842743a2400600.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论