What is the pythonic way of iterating simultaneously over two lists?
Suppose I want to compare two files line by line (compare each ith line in one file with the ith line of the other file), I would want to do something like this:
file1 = csv.reader(open(filename1),...)
file2 = csv.reader(open(filename2),...)
for line1 in file1 and line2 in file2: #pseudo-code!
if line1 != line2:
print "files are not identical"
break
What is the pythonic way of achieving this?
Edit: I am not using a file handler but rather a CSV reader (csv.reader(open(file),...)), and zip() doesn’t seem to work with it…
Final edit: like @Alex M. suggested, zip() loads the files to memory on first iteration, so on big files this is an issue. On Python 2, using itertools solves the issue.
In Python 2, you should import itertools and use its izip:
with the built-in
zip, both files will be entirely read into memory at once at the start of the loop, which may not be what you want. In Python 3, the built-inzipworks likeitertools.izipdoes in Python 2 — incrementally.