0

I'm a little bit confused. What exactly does [:] in this code do when used with an assignment?

l1 = [1, 2, 3]
l2 = [1, 2, 3]

def test(l1, l2):
    l1 = [0]
    l2[:] = [0]

test(l1, l2)
# l1 = [1, 2, 3]
# l2 = [0]

When I use l2[:] = [0], is it like:

def test(l1, l2):
    global l1
    l1 = [0]
    l2 = [0]

Or does it have another meaning? Thank you!

user3265447
  • 123
  • 2
  • 9
  • 1
    What is the point of `text`? – Scott Hunter Sep 09 '20 at 19:30
  • just a mistake :) meant to be test – user3265447 Sep 09 '20 at 19:40
  • 1
    They are very different. This is not a scope issue, so `global` has nothing to do with it. `l1[:] = [0]` modifies the list `l1` by setting it to `[0]`. That is, it replaces all existing elements with the single element `0`, but it does *not* create a new list. It modifies the existing list, so all references to that list will reflect the change. – Tom Karzes Sep 09 '20 at 19:42
  • So basically it looks for l1 in the scope to modify. If it cannot find l1, it looks for it outside the scope? – user3265447 Sep 09 '20 at 19:47
  • 1
    Python uses a fairly simple set of scope resolution rules. If a variable is assigned to within a function body, then that variable is local to that function (unless declared `global` or `nonlocal`). If it is accessed, but not assigned to, then it looks in the current scope, and if absent, looks in a higher-level scope. But note that `x = y` assigns to the variable `x`, while `x[:] = [y]` does not. The latter modifies what `x` refers to, but does not modify `x` itself. – Tom Karzes Sep 09 '20 at 20:00

0 Answers0