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,649
  • 7
  • 29
  • 42
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
  • 124,992
  • 159
  • 614
  • 958