s11010
s11010

Reputation: 23

Is there any way to make an element in a list equal all integers?

I am trying to get these two list to equal one another:

a = [None, 3, 4, 5, 8, 9, None, 0, -3, 2, None, None, None]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]
if a == b:
    print("yay or sth")

Currently I have None as a placeholder. other than using a for loop and checking every single one, is there any way to achieve that?

Upvotes: 1

Views: 554

Answers (2)

Michael M.
Michael M.

Reputation: 11080

As chepner noted in the comments, you could create a class with a __eq__ method that always returns True. Then you could create a global variable with an instance of the class and use, like this:

class EqualClass():
    def __eq__(self, obj):
        return True


Equal = EqualClass()

a = [Equal, 3, 4, 5, 8, 9, Equal, 0, -3, 2, Equal, Equal, Equal]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]

Or, as Kelly Bundy pointed out in a comment, you can use unittest.mock.ANY (source code). Like this:

from unittest.mock import ANY

a = [ANY, 3, 4, 5, 8, 9, ANY, 0, -3, 2, ANY, ANY, ANY]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]
print(a == b)  # => True

However, be sure to see chepner's answer regarding transitivity and why this may be a bad idea.

Upvotes: 2

chepner
chepner

Reputation: 532053

== is supposed to be transitive: if a == b and b == c, then a == c. But such a placeholder would violate that.

Better to simplify define another function to make the comparison you want instead of making __eq__ do something it should not.

def basically_equal(l1, l2):
    return all(x is None or y is None or x == y for x, y in zip(l1, l2))

if basically_equal(a, b):
    print("a and b equal up to placeholder values")

Upvotes: 3

Related Questions