1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

3

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))
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30