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
  • First of all, you're not doing anything with `nums = ` in the _helper_ function on the first example. Is that the same on your actual code? – Prav Dec 30 '21 at 01:43
  • 2
    I suspect you meant `nums = x` in the first code sample. – Mark Dec 30 '21 at 01:44

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