Purify


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#


No error just seeking some clarity


Would like to get some clarity on [:] used in the code and reason for it's use.


def purify(num_list):
    
    for i in num_list[:]:
        if i%2!=0:
            num_list.remove(i)
    return num_list
    
print purify([4,5,5,6])


#3

it is crucial for the success of your code, [:] is normally used for slicing:

num_list = [4,5,5,6]
print num_list[0:1]

this however doesn't modify the list:

num_list = [4,5,5,6]
print num_list[0:1]
print num_list

because you don't specify any numbers in the [:] it takes the entire list, because you are looping over a copy of the list, and remove the values from the original list, you are good. so [:] make sure you are looping over a copy of the list.

You could also do:

for i in num_list[0:len(num_list)]:

this way you can see better what you are copying.

@tekkie1618, that is not an answer to the question asked?


#4

Hi stetim94, thank u for the insight. So without the [:] would the list be modified?


#5

you still modify the list by removing items, but you loop over a copy of the list, which is a crucial difference.

if you where just do this:

for i in num_list:

it wouldn't work, why not? Lets say we have this list:

[4,5,5,6]

we have two 5's, at index 1 and index 2. the moment the for loop arrives at index 1, the 5 gets removed. however, the 5 from index 2 now shifts to index 1 and the for loop continues to index 2 (which now hold 6, thanks to the index shift). the second 5 gets skipped because of index shift if you where just to loop over the list

However, you loop over a copy of the list. the 5 in the original list gets removed, but not in the copy of the list. which means in the copy of the list, there is no index shift. Which is why your code works


#6

understood thank u very much


#7