-1

We know that lists in Python are mutable objects. However, the following code does not change the value of the list whose value is being modified inside a function.

def change(l):
    l=l[2:5]
    return()
l=[1,3,4,5,2,10]
change(l)
print (l)

I expected an output [4,5,2] but it's showing the results [1,3,4,5,2,10].

  • 4
    `l=l[2:5]` replaces the local reference to point to a new list. It doesn't modify the original list at all – UnholySheep Mar 29 '19 at 19:03
  • 2
    The `l` inside your function is a different name than the `l` outside. All you are doing is reassigning the name to a new reference. You could do something like `l[:]=l[2:5]` instead. Or return a new list `return l[2:5]` and reassign outside the function: `l = change(l)` – Mark Mar 29 '19 at 19:03

4 Answers4

1

Exactly as UnhloySheep and Mark Meyer states, changing the code from

l = l[2:5]

to

l[:] = l[2:5]

should fix your issue. You complete code should be:

def change(l):
   l[:]=l[2:5]
return()

l=[1,3,4,5,2,10]
change(l)
print (l)

this print as your answer.

[4, 5, 2]

César Correa
  • 178
  • 1
  • 2
  • 11
0

As you mutate the list inside a function, you will need to return the updated list like:

def change(l):
    l=l[2:5]
    return l
0

You aren't mutating the list; you are just changing the value of the local variable l. Instead, modify the object referenced by that variable.

def change(lst):
    del lst[5:]  # or lst[5:] = []
    del lst[:2]  # or lst[:2] = []
    # or just l[:] = l[2:5], which I forgot about until reading César Correa's answer


some_list = [1,3,4,5,2,10]
change(some_list)
print (some_list)
chepner
  • 497,756
  • 71
  • 530
  • 681
0
def change(l):
   l[:] = l[2:5]

The above code will work.

Normal slicing changes the reference of the list after slicing. You can check this by using id() before and after slicing

Suresh Kumar
  • 364
  • 3
  • 7