Question

I want to find out if there is a way to count the number of iterations that have occurred with the code below:

with open(filename1) as file1, open(filename2) as file2:
    for line1, line2 in zip(file1, file2):
Was it helpful?

Solution

You can do that using enumerate:

with open(filename1) as file1, open(filename2) as file2:
    for i, (line1, line2) in enumerate(zip(file1, file2)):

Here i will be the number of iterations that you have run. More correctly, i will be the index of line1 and line2 in the zipped list which for your purpose is essentially the same. Note however that on the first iteration, i will be 0 not 1. More generally, on the nth iteration, the value of i will be n-1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top