(x, y) == tuple(zip(*zip(x,y)))
is true if and only if the two following statements are true:
x
and y
have the same length
x
and y
are tuples
One good way to understand what's going on is to print at each step:
x = [1, 2, 3]
y = ["a", "b", "c", "d"]
print("1) x, y = ", x, y)
print("2) zip(x, y) = ", list(zip(x, y)))
print("3) *zip(x, y) = ", *zip(x, y))
print("4) zip(*zip(x,y)) = ", list(zip(*zip(x,y))))
Which outputs:
1) x, y = [1, 2, 3] ['a', 'b', 'c', 'd']
2) zip(x, y) = [(1, 'a'), (2, 'b'), (3, 'c')]
3) *zip(x, y) = (1, 'a') (2, 'b') (3, 'c')
4) zip(*zip(x,y)) = [(1, 2, 3), ('a', 'b', 'c')]
Basically this is what happens:
- Items from
x
and y
are paired according to their respective indexes.
- Pairs are unpacked to 3 different objects (tuples)
- Pairs are passed to zip, which will again, pair every items based on indexes:
- first items from all inputs are paired:
(1, 2, 3)
- second items from all inputs are paired:
('a', 'b', 'c')
Now you can understand why (x, y) == tuple(zip(*zip(x,y)))
is false in this case:
- since
y
is longer than x
, the first zip operation removed the extra item from y
(as it couldn't be paired), this change is obviously repercuted on the second zipping operation
- types differ, at start we had two lists, now we have two tuples as
zip
does pair items in tuples and not in lists
If you're not 100% certain to understand how zip
work, I wrote an answer to this question here: Unzipping and the * operator