Is it true that function parameters in Python are mutable and global?

I’m a Python novice. Suppose I have a function myfun that takes a parameter lst. The following example seems to show that function parameters are mutable and global. Is this correct?

  1. In the example below, the parameter lst is mutable because I can make changes to its value (e.g., I can append an element).
  2. In the example below, the parameter lst is global because if I define a variable, with the same name, outside the function, the variable lst is modified if the parameter lst is modified within the function myfun. To my novice eyes, this is surprising behavior; does anyone have insight on this?
# Define a function that modifies the value of its parameter
def myfun(lst):
  lst.append(100)
  return lst

# Test the function
lst=[1,2,3]
print(lst)
print(myfun(lst))
print(lst)

The code above gives this output:

[1, 2, 3]
[1, 2, 3, 100]
[1, 2, 3, 100]

Whether or not they’re mutable would depend on the data type in question. Lists are mutable and you can mutate them inside a function but that wouldn’t change the function in the future, just the original list object you passed.

I think the name re-use just confuses the issue, you could equally write the following at the module level for the same output-

gname = [1, 2, 3]
print(gname)
print(myfun(gname))
print(gname)

Nothing about the actual function has changed here. You have mutated the list object you passed in though.

You can use id to display exactly what object you’re dealing with, the one you pass to your function is the same as returned. You’ve merely added another name to that object for the duration of the function.

2 Likes

@tgrtim has, I think, explained why what you think you’re seeing isn’t quite what you’re seeing… but there is a similar thing with loops which might interest you.

Not quite the same, but kinda the same… the variable you use when iterating with a for loop (for variable in iterable) isn’t cleared once the loop exits…

items = ["apple","banana","guava","lemon","mango","orange","pear"] for item in items: print(f"The current item is {item}") print("What was that last item again?") print(f"Oh yeah! It was '{item}'!") items.sort(reverse=True) for number, item in enumerate(items): print(f"Item #{number+1} on my list: {item}!") print(f"Great, I've got {number+1} items to get. Better not forget the {item}!")
2 Likes