equality and not equality operators in Python

Question:

Let’s say I have these two lists:

number_list_1 = [1, 2, 3, 4, 5]
number_list_2 = [1, 2, 3, 4, 5]

then let’s say that I want to know if the two lists are equal (There are a lot of ways to do this in Python and it’s not what I’m looking for, also this is not a good approach in Python to do this)

solution 1:

def list_equality_1(l1, l2):

    # Assuming that two array like objects have the same length
    length = len(l1)

    for i in range(length):
        if l1[i] == l2[i]:
            continue
        else:
            return False
    return True

solution 2:

def list_equality_1(l1, l2):

    # Assuming that two array like objects have the same length
    length = len(l1)

    for i in range(length):
        if l1[i] != l2[i]:
            return False
    return True

In both of these solutions, each time we loop, we are evaluating the if statement, for the first one we are evaluating for equality and for the second one we are evaluating for not equality of the elements in the ith place.
My question is which one is better? evaluating for the ‘equality’ first and use else statement, or evaluating for the ‘not equality’? I want to know how the compiler deals with this.

Asked By: winter

||

Answers:

My question is which one is better?

My answer is that the second one is better.

  • You waste less lines
  • Everybody knows the continue is anyway implicit

I always use the second code when I have to, even thought as you said before there are several other ways to compare lists in Python, I’m talking of C/C++.


length = len(l1)

for i in range(length):
    if l1[i] != l2[i]:
        return False
return True

This code is uselessy verbose, I would shorten it this way.

for first, second in zip(l1, l2):
    if first != second:
        return False
return True

It could be useful to you the reading of the documentation about built-in class zip.

By default, zip() stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable.

So this alternative method will only work with len(l1) == len(l2), but this is true with your code too.


As I said before I want to know how the compiler deals with equality (==) and not equality (!=) operators.

Well, I don’t think you ever compile your Python code, that’s why you don’t have an .asm, .o or .exe file to inspect.

I want to know the complexity of these operators.

They both have temporal complexity of O(1).

Disassembly


Do you see any difference?

The two are equivalent, they generate almost the same set of instructions, except for a couple of things after line 100, but it won’t affect the performance.

Answered By: FLAK-ZOSO