0

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

2
  • your function needs to return the modified list and reassign it at the caller. Commented Dec 8, 2022 at 15:18
  • Does this answer your question? Does a slicing operation give me a deep or shallow copy? Commented Dec 8, 2022 at 15:24

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

"a completely new List unrelated to L" - no exactly: the strings are still the same instances. If OP would mutate L[i] instead of assign to it then it would work.
@luk2302, you can't mutate strings. It is the list itself the the OP wants to change.
2

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.

Comments

2

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)

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.