0

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()
Ugnius Malūkas
  • 2,426
  • 6
  • 28
  • 40
James Zhu
  • 1
  • 1

1 Answers1

4

Because strings are immutable. You cannot edit strings, you can just create new strings.

Source: Python Docs

See also: Function calls in Python

Martin Thoma
  • 108,021
  • 142
  • 552
  • 849