python不可变变量,如何使变量在python中不可变

My python script:

N = 2 # 2*2 matrix

a = N * [0]

b = a

print(b) # prints [0, 0]

for i in range(N):

a[i] = N * [0]

for i in range(N):

for j in range(N):

a[i][j] = 0

print(a) # prints [[0, 0], [0, 0]]

print(b) # prints [[0, 0], [0, 0]]

Why does my second print(b) change? How to make it immutable? I'd like my b to still contain [0, 0].

解决方案

Your understanding of "objects" in Python and variable assignments is flawed.

In a language like C, when you define a variable (say int a), a tiny area of memory is allocated and reserved for this variable and a is now something that refers to this area of memory. You can poke into this area, change it and find that a "has a" different value now. A statement like a = 2 (or a = b where b is another variable) takes the value of the right hand side and writes it into the memory location reserved for a. Now you can modify b as you wish but a will still retain the original value. This is why you can do things like a++ in C which means, "get the value of what a refers to, add one to it and write it back to the same location".

In Python, when you say x = [], a new list object is created and x is made to "point" to that list. Now any change you make to x is affecting this object. Suppose you say y = x, you will get another reference to the same object. Changing y (or x for that matter)

will change the object which is now pointed to by x and y. This is what you've done with the B = A assignment. All things done to this object via A will be visible when you access it via B since they both point to the same object. In this sense, all variables in Python are like pointers in C. You can also understand why we don't have a ++ operator in Python since it's meaningless to modify the contents of a memory location like in C.

The solution suggested by others so far is suggesting that you make a new object with the exact same contents as the list pointed to by A and make B point to this copy. This way, if you modify A (or what A points to), B (or what B points to) will remain unchanged.

This however doesn't make B "immutable" (i.e. an object which cannot be modified in place). However, I think you have simply used the word erroneously and meant that you didn't want the aliasing to take place.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值