0
def main():
    a = [1, 2, 3]
    myFunc(a)
    print(a)

def myFunc(myList):
    myList[1] = 100

Im studying for my final for my first compsci class about python. This code came up and I dont understand why the value of the list changes when the myFunc() doesnt have a return value. Why doesn't it just print out 1,2,3? Thank you for your time.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

2 Answers2

1

Python lists are mutable. Python functions pass arguments by assignment. When you call main it creates a list and associates it with the local (to main) name a. It then calls myFunc, which assigns this same list as the value of the local (to myFunc) name myList, which mutates it. (I.e., no copy of the list is made; myFunc is working with the same mutable object.) Control then flows back to main, which prints the (now changed) value of a.

Alan
  • 9,410
  • 15
  • 20
0

I'm currently taking an intro class to Python too so I'll just try my best to answer this question.

Simply put, not all functions need to return a value.

In your function, MyFunc, you effectively changed the list without having to return a value. You just took an extra step to make your program more organized. It would be the same if you just had the contents of your function inside the main function.

Kai Mou
  • 284
  • 3
  • 20