user2979044
user2979044

Reputation: 306

Python: Comparing elements of a list within a list appears to be returning wrongly

Just coding a file comparison program, and came upon this issue. I can't even begin to comprehend why this is happening. I did my best to google and search for the issue, but it's a little hard. When this code runs:

while a < len(filehashes) and b < len(inphashes):
    if filehashes[a][1] == filehashes[b][1]:
        print(filehashes[a][1] + ' == ' + inphashes[b][1])
        a += 1
        b += 1
    else:
        print('Inconsistency error')

I get this output:

ee53f15519619c51f205553c828e7546 == ef53f15519619c51f205553c828e7546

filehashes and inphashes are both list of list of str (i.e. [['honk','donk'],['bonk','ponk']]).

And while that is the expected content of filehashes[a][1] and inphashes[b][1]. They obviously don't actually equal each other ('ee...' != 'ef...'). What on earth is causing this and how do I fix it?

Upvotes: 0

Views: 58

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You are not comparing filehashes[a][1] == inphashes[b][1]. You are comparing:

if filehashes[a][1] == filehashes[b][1]:

Note the names, you are indexing into the same structure here. If a == b that is guaranteed to be comparing the same object even, but it'll be True for any repeated hash values.

Perhaps you instead meant:

if filehashes[a][1] == inphashes[b][1]:

If all you do is increment a and b at the same time and they remain equal, you could just as well use zip here:

for fhash, inphash in zip(filehashes, inpuhashes):
    if fhash[1] == inphash[1]:
        print('{} == {}'.format(fhash[1], inphash[1]))
    else:
        print('Inconsistency error')

Upvotes: 1

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

The if condition is filehashes[a][1] ==filehashes[b][1] while the print line is print(filehashes[a][1] + ' == ' +inphashes[b][1]). Note the difference. I'm not clear on what you are asking. I think this answers it. If it doesn't, comment on this and then I'll delete this answer.

Upvotes: 1

Related Questions