How to modify a list in the global scope using a function? Python 3

1
def lsum(x):
    res = []
    for i in x:
        res.append(x+1)
    L = res
L = [1,2,4]
lsum(L)
print(L)

How can I modify the above code without using global L so that print ("L") "returns" [2,3,5]? That is, I want to modify the L list inside the function and take the modifications to the global scope. I'm new to python so thanks for simple answers.

    
asked by anonymous 12.02.2017 / 03:57

1 answer

2

Just return the value and assign it to the variable L again:

def lsum(x):
    res = []
    for i in x:
        res.append(i+1)              # <- Aqui é i+1, não x+1
    return res                       # <- Retornando o valor

L = [1,2,4]
L = lsum(L)                          # <- Atribuindo o valor retornado a L
print(L)

You can still generate the same result using list compression:

def lsum(x):
    return [i+1 for i in x]

L = [1,2,4]
L = lsum(L)
print(L)

Or functions :

lsum = lambda x: [i+1 for i in x]

L = [1,2,4]
L = lsum(L)
print(L)

I have listed the three forms so that it can serve as a guide for future studies. Look into algorithm materials before you start the study in a language, since it lacks many basic concepts.

  

The programming language is like a tool of work: a means of making art in the hands of those who know how to use it or a weapon in the hands of those who do not know.

    
12.02.2017 / 04:11