0

Hello guys I couldn't understand the difference between the working principles of these two functions. changeName() function doesn't change "name" as "david", it still says "matt". But change() function does change the cities list's first element. Can you help me please?

def changeName(n):
    n = "david"
name="matt"
changeName(name)
print(name)

def change(a):
    a[0] = "istanbul"
cities=["paris","berlin"]
change(cities)
print(cities)
  • The difference is that in the first case you're assigning to a local variable (parameters are local variables), and in the second you're assigning to an index, which calls the `__setitem__` method on `a`. Note that both strings and lists are reference types in Python (in fact I don't think Python has any value types) and that if you change the body of the second function to `a = ["istanbul"]`, it will act the same as the first function even though you're still dealing with lists. – sepp2k Aug 31 '21 at 12:37
  • ```n``` parameter is over riden by the new definition of ```n``` in the function –  Aug 31 '21 at 12:37
  • Thank you for your answers, they helped a lot :) – ahmetfrkozdemir Aug 31 '21 at 21:01

0 Answers0