When I have to compare the contents of two array-like objects -- for instance list
s, tuple
s or collection.deque
s -- without regard for the type of the objects, I use
list(an_arrayish) == list(another_arrayish)
Is there any more idiomatic/faster/better way to achieve this?
Compare it elementwise:
def compare(a,b):
if len(a) != len(b):
return False
return all(i == j for i,j in itertools.izip(a,b))
For Python 3.x, use zip
instead
Tuples appear to be faster:
tuple(an_arrayish) == tuple(another_arrayish)
Here's a quick benchmark:
>>> timeit.Timer('list(a) == list(b)', 'a, b = (1, 2, 3, 4, 5), (1, 2, 3, 4, 6)').timeit()
2.563981056213379
>>> timeit.Timer('list(a) == list(b)', 'a, b = [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]').timeit()
2.4739551544189453
>>> timeit.Timer('tuple(a) == tuple(b)', 'a, b = (1, 2, 3, 4, 5), (1, 2, 3, 4, 6)').timeit()
1.3630101680755615
>>> timeit.Timer('tuple(a) == tuple(b)', 'a, b = [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]').timeit()
1.475499153137207
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