简体   繁体   中英

Python - Why this list doesn't change

I want to change a part of a list and save the result. I would like to know why this method is not working. And Thank you!

Code:
def Test(L):
    for i in range(len(L)):
        L[i] = L[i][1:]

L = ["-stackoverflow", "-Python", "-C++"]
Test(L[1:])
print(L)
Ouput:

['-stackoverflow', '-Python', '-C++']

Expected:

['-stackoverflow', 'Python', 'C++']

You call the Test() function with L[1:] , but this is only a copy of the list and not the original L list. So when you modify the list in your function, you modify the copy.

Whenever you use [:] on a list, it constructs a new list. When you called Test(L[1:]) , you didn't pass it L but rather a completely new List unrelated to L . There are two things you can do here: Either return the new list for reassignment or pass L into Test() and not L[1:] .

your function needs to return the modified list and reassign it at the caller.

def Test(L):
    for i in range(len(L)):
        L[i] = L[i][1:]
    return L

L = ["-stackoverflow", "-Python", "-C++"]
L = Test(L[1:])
print(L)

you just need to write Test(L) and not Test(L[1:]) as the function is already doing the operation for you.

 def Test(L):
   for i in range(len(L)):
     L[i] = L[i][1:]

L = ["-stackoverflow", "-Python", "-C++"]

Test(L)
print(L)

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