Avinash D
Avinash D

Reputation: 13

zip objects created using the same iterables not equal. Why?

Why two zip objects (made using same two iterables) aren't equal?

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
a = zip(list1, list2)
b = zip(list1, list2)
print(a == b)

The above code is printing False.
Shouldn't it give `True' since the zip objects are similar?

Upvotes: 0

Views: 161

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45741

The returned zip object is an iterator. To be able to test the value equality of it, potentially the entire iterator would need to be walked, which would exhaust it, so you'd never be able to use it after. And if only part of the iterator was walked during the test, it would be left in a "difficult to determine state", so it wouldn't be usable there either.

I'm not sure if zip is considered to be a "user-defined class", but note this line in the docs:

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves)

In theory they could have made a workaround that would allow equality testing of a zip object (in cases where the object that was zipped wasn't itself an iterator), but there was likely no need. I can't think of a scenario where you would need to test such a thing, and where comparing the object forced as a list isn't an option.

Upvotes: 1

Related Questions