简体   繁体   中英

NameError when appending to a List inside a function (Python)

Why do I get the error NameError: name 'l1' is not defined when I run the code below, will placing the l1 and l2 empty lists outside the functions allow me to append/use the return statements?

def function():
    l1 = []
    l2 = []
    for x in range(1):
        if 3 > 2:
            l1.append(1)
            l2.append(2)
    return l1, l2

call = function()
print(l1)
print(l2)

You can't call it like that, l1 and l2 are undefined then, so need to do:

def function():
    l1 = []
    l2 = []
    for x in range(1):
        if 3 > 2:
            l1.append(1)
            l2.append(2)
    return l1, l2

l1,l2 = function()
print(l1)
print(l2)

Output:

[1]
[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM