[Solved] the difference between zip and enumerat in for loop? [closed]


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:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

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 the elem_l list is deleted from, there are fewer elements to produce. You’d get the same outcome if you produced a copy of elem_l instead:

for i, e in enumerate(elem_l[:]):

where the [:] identity slice produces a new list, independent of the original elem_l list you then delete from in the loop.

1

solved the difference between zip and enumerat in for loop? [closed]