About External list variable += and Methods append() extend() in function

ls = []

def test1(element):
    ls.append(element)

def test2(element):
    ls.extend([element])

def test3(element):
    ls[len(ls):len(ls)] = [element]

def test4(element):
    ls += [element]

test1(1)
test2(1)
test3(1)
test4(1)

run the test4 will get error:

E:\PyStudy\cpython>.\python.bat -m test.py -j3
Running Debug|x64 interpreter...
Traceback (most recent call last):
  File "E:\PyStudy\cpython\Lib\runpy.py", line 189, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\PyStudy\cpython\Lib\runpy.py", line 112, in _get_module_details
    __import__(pkg_name)
  File "E:\PyStudy\cpython\test.py", line 18, in <module>
    test4(1)
  File "E:\PyStudy\cpython\test.py", line 13, in test4
    ls += [element]
    ^^
UnboundLocalError: cannot access local variable 'ls' where it is not associated with a value

I don’t know why the error happened,I checked the official documentation, which says that the effect of extend() and += should be the same.

The difference from the other test functions is that here you are referring to ls in an “assignment context”. left of = or here +=, so Python will create a local variable, which is not initialised when you first read it.

This would do what you want.

def test4(element):
    global ls
    ls += [element]
1 Like

Be sure to note that if an assignment is made to a name within a function, that name is considered to be local throughout the function, unless it is declared otherwise. This applies even where the name appears in statements that precede the first assignment to it within that function.

Here is an example:

ls = []

def test4(element):
    print(ls)
    ls += [element]

test4(1)

Part of the error message:

line 4, in test4
    print(ls)
UnboundLocalError: cannot access local variable 'ls' where it is not associated with a value

In this case, it was the passing of ls to the print function that raised the error, because even though that preceded the assignment, the name ls was considered local throughout the function.

Thanks for your answers ::

The issue is with += (which is a form of assignment), not with anything to do with lists or their methods. See the canonical Q&A on Stack Overflow: python - UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use) - Stack Overflow (I have personally done a fair bit of work to improve the question, and added my own answer here).

1 Like