schickb schickb - 2 months ago 6x
Python Question

Elegant way to compare sequences

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.


Convert both sequences to lists, and use builtin list comparison. It should be sufficient, unless your sequences are really large.

list(a) == list(b)


Testing done by schickb shows that using tuples is slightly faster:

tuple(a) == tuple(b)