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:
You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following:
all(x == y for x, y in itertools.izip_longest(a, b))
Note that if the two iterables are not the same length, the shorter one will be padded with None
s. In other words, it will consider [1, 2, None]
to be equal to (1, 2)
.
Edit: As Kamil points out in the comments, izip_longest
is only available in Python 2.6. However, the docs for the function also provide an alternate implementation which should work all the way back to 2.3.
Edit 2: After testing on a few different machines, it looks like this is only faster than list(a) == list(b)
in certain circumstances, which I can't isolate. Most of the time, it takes about seven times as long. However, I also found tuple(a) == tuple(b)
to be consistently at least twice as fast as the list
version.