0

I try modifying the list li with function abc

li = [0, 0]
def abc(x):
    li = 8

abc(5)
li

which returns [0, 0]. On the other hand,

li = [0, 0]
def abc(x):
    li[0] = 8

abc(5)
li

returns [8, 0]. Could you please explain why such micro modification takes effect?

Akira
  • 2,594
  • 3
  • 20
  • 45
  • 2
    In your first example you create a new local variable named `li`. In the second example you don't define a new local variable, so Python searches in the surrounding scope, finds the global `li` and modifies that. – Matthias May 20 '21 at 06:24
  • Thank you so much for your clear and succinct answer @Matthias – Akira May 20 '21 at 06:25

0 Answers0