The code is here, it deletes some element in a list. What is the difference of zip and enumerate in the loop condition? It seems that enumerate yield wrong result.
def delete(elem_l, del_e):
n_del = 0
for e, i in zip(elem_l, range(len(elem_l))):
# for i, e in enumerate(elem_l):
print "cycle:", i, "elem:", elem_l[i - n_del], "len:", len(elem_l)
if e == del_e:
del elem_l[i - n_del]
n_del += 1
elem_list = [1, 2, 3, 4, 3, 5, 5, 4, 3]
delete(elem_list, 3)
At issue here is your use of the
zip()
function. It produces a list of tuples up front. You created a copy of the original list with numbers added. From the documentation:Emphasis mine.
Thus, altering the
elem_l
in the loop does not affect the loop iteration count.enumerate()
on the other hand produces indices on demand, and as theelem_l
list is deleted from, there are fewer elements to produce. You'd get the same outcome if you produced a copy ofelem_l
instead:where the
[:]
identity slice produces a new list, independent of the originalelem_l
list you then delete from in the loop.