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

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Ghoudiy
  • 15
  • 6
  • your function needs to return the modified list and reassign it at the caller. – Sembei Norimaki Dec 08 '22 at 15:18
  • Does this answer your question? [Does a slicing operation give me a deep or shallow copy?](https://stackoverflow.com/questions/19068707/does-a-slicing-operation-give-me-a-deep-or-shallow-copy) – luk2302 Dec 08 '22 at 15:24

4 Answers4

1

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.

Gandhi
  • 346
  • 2
  • 9
1

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

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • *"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 Dec 08 '22 at 15:22
  • 1
    @luk2302, you can't mutate strings. It is the list itself the the OP wants to change. – Daniel Walker Dec 08 '22 at 15:28
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)
Sembei Norimaki
  • 745
  • 1
  • 4
  • 11
1

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)
attacker88
  • 11
  • 5