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

Should setting A to B then changing A affect B in python? - Stack Overflow

programmeradmin0浏览0评论
a = [0,0]
b = a
a[0] = 1
print(b) 

This code returns [1,0]

Shouldn't it return [0,0]?

Is there any way to bypass this bug/feature? (to have it return [0,0])

I probably have used code very similar to this in the past, there weren't any problems before...

a = [0,0]
b = a
a[0] = 1
print(b) 

This code returns [1,0]

Shouldn't it return [0,0]?

Is there any way to bypass this bug/feature? (to have it return [0,0])

I probably have used code very similar to this in the past, there weren't any problems before...

Share Improve this question edited Feb 21 at 2:18 wjandrea 33.2k10 gold badges69 silver badges98 bronze badges asked Jan 30 at 19:37 Allen LanAllen Lan 11 bronze badge 2
  • 4 Not a bug. See How do I clone a list so that it doesn't change unexpectedly after assignment? – Guy Incognito Commented Jan 30 at 19:41
  • 1 See Facts and muths about python names and values – Ahmed AEK Commented Jan 30 at 19:48
Add a comment  | 

1 Answer 1

Reset to default 1

this is not a bug, it's how Python handles mutable objects like lists.

since b is assigned to a, both variables point to the same list in memory. Changing a affects b because there is only one list.

you can use a.copy(),this creates a new list with the same values

a = [0,0]
b = a.copy()
a[0] = 1
print(b) 

Other methods mentioned in this answer

发布评论

评论列表(0)

  1. 暂无评论