Home > database >  Python - Why this list doesn't change
Python - Why this list doesn't change

Time:12-08

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 ']

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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:].

  • Related