Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best ways to compare the contents of two list-like objects?

When I have to compare the contents of two array-like objects -- for instance lists, tuples or collection.deques -- 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?

like image 855
Erik Avatar asked Aug 27 '12 01:08

Erik


2 Answers

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

like image 165
JBernardo Avatar answered Nov 02 '22 23:11

JBernardo


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
like image 24
Ry- Avatar answered Nov 02 '22 23:11

Ry-