最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0
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()
发布评论

评论列表(0)

  1. 暂无评论