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

Asked

Viewed 79 times

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 to print("L") "return" [2,3,5]? That is, I want to modify the list L within the function and take the modifications to the global Scope. I’m new to python so I appreciate simple answers.

1 answer

2

Just return the value and assign the L variable 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 even functions lambda:

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

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

I have indicated the three ways in which it can serve as a direction for future studies. Look for materials from algorithms before you start studying in a language, as you apparently lack many basic concepts.

Programming language is like a working tool: 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.