Why we do not directly modify a list we are given as input?


#1

"Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result.

For example, purify([1,2,3]) should return [2].

Do not directly modify the list you are given as input; instead, return a new list with only the even numbers."

===> why we do not directly modify a list we are given as input ?
def purify(a_list):
for each in range(len(a_list)):
if a_list[each] % 2 != 0:
del(a_list[each])

return a_list

why it wrong ?
thanks


#2

You might not want the input to be changed if you need it for something else as well.

It's faster to create a new list without the unwanted values anyway, because removing a value from a list involves moving all the values that come after to fill up the space from the removal.

For example, if you have [1, 2, 6, 8, 5], and you remove 6, the 8 and 5 would each be moved one step to the left which takes time proportional to the number of elements that follow. (And finding the value takes time as well, so the remove method takes time proportional to the length of the list.

The fastest way to create a new list without the odd numbers is to use list comprehension which is brought up later in the course.

If you really wanted to remove from the original data, you would want a different data type but it's a trade-off because no data structure does everything. For example, a dict has fast removal, but doesn't represent any order between the values. There's also OrderedDict, but that most likely has a speed trade-off somewhere so it's still no magical solution.

Also, del is not a function, so you should not have parentheses there, that's like writing the number 5 like this: (5), it's just weird.

Further, you'll have to watch out when removing from the list that you are currently iterating through because elements will be moved and the length will change when you remove elements.

And.. take care to mark your code as pre-formatted text when you post it on a forum since forums typically have a bunch of formatting rules that will mess up your code and you don't want to post a bunch of garbage that won't run.