Why can't I reassign a list (passed as a paramater) in a function?

Viewed 44

According to my understanding, both functions should have changed list since lists are mutable but only foo() did so.

def foo(myList):
  myList[0] = 3
  
def bar(myList):
  myList = [3,2,1]

list = [1,2,3]
print(list)

foo(list)
print(list)

bar(list)
print(list)
1 Answers

Print the id may help you to understand it:

def foo(myList):
  myList[0] = 3
  print(id(myList))
  
def bar(myList):
  myList = [3,2,1]
  print(id(myList))

list = [1,2,3]
print(list)
print(id(list))

foo(list)
print(list)
print(id(list))

bar(list)
print(list)
print(id(list))
Related