thh32
thh32

Reputation: 77

Count iterations that have occured in python

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):

Upvotes: 2

Views: 90

Answers (1)

sshashank124
sshashank124

Reputation: 32189

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

Upvotes: 4

Related Questions