Why Python function can modify list
or dict
but not a string
outside:
this makes sense, because function create scope, so the setit function create new variable:
ttt = 'ttt'
def setit(it):
ttt = it
print(ttt)
def showit():
print(ttt)
if __name__ == "__main__":
setit("lsdfjlsjdf")
showit()
But how to explain this, the setit function can modify the list outside:
aaa = []
def setit(it):
ttt = it
aaa.append(it)
def showit():
print(aaa)
if __name__ == '__main__':
setit(123)
showit()
setit(234)
showit()