简体   繁体   中英

Is it possible to modify a list that exists outside of the scope of a function?

So, I am trying to modify a (global?) list within a function. However, the list exists outside the scope of the function so when I call the function it doesn't actually modify the list. I have tried using the 'global' keyword, and have tried making a copy of the existing list and then modifying that, but nothing is working. Any suggestions? This is python by the way.

Lists are mutable, pass them in and have at it.

def list_modifier(passed_list):
    for i in range(len(passed_list)):
        passed_list[i] += 1
test_list = [5, 6, 7]
print(test_list)  # [5, 6, 7]
list_modifier(test_list)
print(test_list)  # [6, 7, 8]

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