python列表可以是变量吗,Python列表不反映变量更改

When I write this code:

polly = "alive"

palin = ["parrot", polly]

print(palin)

polly = "dead"

print(palin)

I thought it would output this:

"['parrot', 'alive']"

"['parrot', 'dead']"

However, it doesn't. How do I get it to output that?

解决方案

Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.

You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.

What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.

You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:

>>> palin[1] = polly

>>> palin

['parrot', 'dead']

Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.

Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".

Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.

Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值