【问题标题】:Why can I sometimes edit some list variables with inner function, but not ints in Python [duplicate]为什么有时我可以用内部函数编辑一些列表变量,但在 Python 中不能编辑整数 [重复]
【发布时间】:2026-02-23 11:55:01
【问题描述】:

例如,如果我使用下面的代码,这不会改变 nums 值

def K():
    nums = 4
    def helper(x):
        nums = 
    helper(3)
    return nums
print(K())

# 4 -> 4

但是,如果 nums 是一个列表,我可以

def K():
    nums = [0]
    def helper(x):
        nums[0] = x 
    helper(3)
    return nums
print(K())

# [0] -> [3]

【问题讨论】:

  • 首先,在第一个示例的 helper 函数中,您没有使用 nums = 做任何事情。你的实际代码也是这样吗?
  • 我怀疑您在第一个代码示例中的意思是 nums = x

标签: python


【解决方案1】:

在第一个示例中,您实际上是在创建一个名为 nums 的变量,它只存在于您的函数 helper

在第二个示例中,helper 正在编辑外部范围内的现有列表。

这就是 Python 中不同元素的作用域的工作方式。外部范围的变量与只读变量一样好。你可以阅读更多here

【讨论】: