1

Can we change a list's value in-place inside a function? The following two pieces of code got me confused.

def change_list(a):
    a[0], a[1] = a[1], a[0]
    return 

a = [1, 2]
change_list(a)
a    # this will output [2, 1]

This function above just swap the first and second element of a list.

However, when I wrap this function inside another function, and try to change a longer list's value by calling the change_list function twice on two sub-lists, the change is no longer in-place.

def change_parts_of_list(longer_a):
    change_list(longer_a[0:2])
    change_list(longer_a[2:4])
    return

longer_a = [1, 2, 3, 4]
change_parts_of_list(longer_a)
longer_a    # this will return [1, 2, 3, 4]

Why doesn't the second function return [2, 1, 4, 3]?

Thanks! A bit of context on this - I was trying to implement quicksort on a Python list and realize I need an assignment statement inside the function. i.e. the following code output the correct results.

def change_list_modified(a):
    a[0], a[1] = a[1], a[0]
    return a

def change_parts_of_list_modified(longer_a):
    longer_a[0:2] = change_list(longer_a[0:2])
    longer_a[2:4] = change_list(longer_a[2:4])
    return longer_a

longer_a = [1, 2, 3, 4]
change_parts_of_list(longer_a)
longer_a
yuqli
  • 4,461
  • 8
  • 26
  • 46
  • 4
    Slicing makes a copy, so you are not passing in the original list. Which is why you found you had to return the value and assign back to the original list. – AChampion Aug 25 '18 at 19:32
  • 1
    Also, if you're modifying in-place, you probably don't want to return anything. – Moses Koledoye Aug 25 '18 at 19:35

0 Answers0