List Comprehension Not Working. Why?

does anyone know why this function does not work correctly?

def remove_odd_numbers_from_list(lst):
lst = [i for i in lst if i % 2 == 0]
return lst

1 Like

If the assignment is to modify the list that is passed as an argument, it does not do that, because your comprehension creates a new list, which, within the namespace of the function only, is also called lst. It does not modify the global lst at all. The function then returns the new list, the original (or global) being unchanged.

To modify a list passed to a function, you must modify the elements of the list, by acessing them through indexing, and no return statement is needed.

2 Likes

thanks so much! i think iā€™m following. so something like this:

def remove_odd(lst):
lst = [lst.remove(i) for i in lst if i % 2 != 0]

1 Like

Yes, but you do not need lst =. The comprehension does the necessary work (via remove()) all by itself. That variable lst inside the function stays inside the function and dies there.

2 Likes