Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:
def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
The following is a bit shorter, but also less efficient since a third sequence is created:
def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.
Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.
Apart from the extra memory used by creating temporary lists/tuples, those answers will lose out to short circuiting generator solutions for large sequences when the inequality occurs early in the sequences
from itertools import starmap, izip
from operator import eq
all(starmap(eq, izip(x, y)))
or more concisely
from itertools import imap
from operator import eq
all(imap(eq, x, y))
some benchmarks from ipython
x=range(1000)
y=range(1000); y[10]=0
timeit tuple(x) == tuple(y)
100000 loops, best of 3: 16.9 us per loop
timeit all(imap(eq, x, y))
100000 loops, best of 3: 2.86 us per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With