2

For example, if I use the following code, this will not change nums value

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

# 4 -> 4

However, if nums is a list, I can

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

# [0] -> [3]
Loki Stark
  • 29
  • 1

1 Answers1

1

In the first example, you're actually creating a variable called nums that only lives inside your function helper

In the second example, helper is editing an existing list from the outer scope.

It's just how scopes work for different elements in Python. Variables from the outer scope are as good as read-only. You can read more here.

luk020
  • 42
  • 4