1

I am trying to write a simple program that looks through two text files and reports any differences between the two files. For this function, I have two lists that contain a list of words for each line (so they're 2D lists). I would like to go through and compare each word and report an error if they are not the same, storing all of the errors in a list that is printed for the user. The i iterator would report the line of the error and then the two words are also reported.

def compare(lines1, lines2):
    for i, line1, line2 in izip(lines1, lines2):
        for word1, word2 in izip(line1, line2):
            if word1 != word2:
                report_error(i, word1, word2)

However, this is not working for me. I read on StackOverflow that I would need to use the zip() or izip() function to read two lists at once but it still isn't working for me. I am getting the following error.

  File "debugger.py", line 28, in compare
    for i, line1, line2 in izip(lines1, lines2):
ValueError: need more than 2 values to unpack

Any idea what I'm doing wrong? I can also provide the full file if that is helpful.

1 Answer 1

4

zip(), and similar functions, produce tuples of a length equal to the number of passed arguments. for word1, word2 in izip(line1, line2): would work, but for i, line1, line2 in izip(lines1, lines2): does not, as you're only zipping through two iterables, lines1 and lines2, so it can't unpack those two-element tuples into three references.

To fix this, use enumerate(), which adds an index. Use start=1 to start with a line number of 1 instead of the default of 0:

def compare(lines1, lines2):
    for i, (line1, line2) in enumerate(izip(lines1, lines2), start=1):
        for word1, word2 in izip(line1, line2):
            if word1 != word2:
                report_error(i, word1, word2)
Sign up to request clarification or add additional context in comments.

1 Comment

@KevinJ.Chase thanks for the tip! new to StackOverflow

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.