Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

Not getting the desired output when using the Python list

When I run this code, output is 11, but my expected output is 10.

a=[10]
b=a
b[0]=11
print(a)

What's the issue? And how do I get my expected output without importing any external module?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because b is a reference to a. Changing any element of a or b are affecting the whole a and b list. To keep the list a always the same, Copy a to b then changing won't affect to a.

a = [10]
b = a.copy() # Also can slice it by b = a[:]
b[0] = 11
print(a)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...