In the previous lecture, we saw that it's inadvisable to iterate through a list while modifying its contents by removing (or inserting) elements. What should be done?

One possibility is to go through the list while creating a new list:

In [1]:
def remove_4pt0(L):
    '''Remove all occurrences of 4.0 from the list L'''
    L_new = []
    for e in L:
        if e != 4.0:
            L_new.append(e)
    L[:] = L_new #Assign L_new to the *contents*
                 #of L -- has an effect outside
                 #the function

L = [3.2, 4.0, 4.0, 2.3, 1.5, 3.9, 4.0]