Home > Net >  why is list modified in function in Python?
why is list modified in function in Python?

Time:11-06

I have the following code:

def recursive_sort(list_to_sort, key):
"""
sort a list by a specified key recursively
"""
if len(list_to_sort) == 1:
    return list_to_sort
for i in range(0,len(list_to_sort) - 1):
    if list_to_sort[i][key] > list_to_sort[i   1][key]:
        list_to_sort[i], list_to_sort[i 1] = list_to_sort[i 1], list_to_sort[i]

return recursive_sort(list_to_sort[:-1], key)   [list_to_sort[-1]]

I run it in main() with the following:

sensor_list = [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 10)]


print("\nOriginal unsorted list\n", sensor_list)
print("\nList sorted by room number\n", recursive_sort(sensor_list, 0))
print("\nList sorted by room name\n", recursive_sort(sensor_list, 1))
print("\nOriginal unsorted list\n", sensor_list)

This prints the output:

Original unsorted list
 [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), 
('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 10)]

List sorted by room number
 [('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4205', 'Tiled Room', 4), 
('4213', 'STEM Center', 0), ('4218', 'Workshop Room', 3), ('Out', 'Outside', 10)]

List sorted by room name
 [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('Out', 'Outside', 10), 
('4213', 'STEM Center', 0), ('4205', 'Tiled Room', 4), ('4218', 'Workshop Room', 3)]

Original unsorted list
 [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('4213', 'STEM Center', 0), 
('4205', 'Tiled Room', 4), ('Out', 'Outside', 10), ('4218', 'Workshop Room', 3)]

Why are the first and fourth prints returning different lists, shouldn't sensor_list remain unchanged?

CodePudding user response:

As @PresidentJamesK.Polk mentions, this is called In-place modification. This means that whatever you do to your parameter / variable, it modifies it outside the function. This occurs because you are modifying the parameter itself and not copying it to the list. To prevent this, in you function you can say:

def recursive_sort(list_to_sort, key):
   result = list_to_sort.copy() # Or just regular assignment, but this is guaranteed to prevent in-place modification
   
   # Subsequent code with 'list_to_sort' replaced with result so
   # that it modifies the new, copied variable instead of the original
  • Related