Conditional Expression with tuple unpacking gives too many values to unpack

x,y = y,x if y>x else x,y
This is to make sure x is always the smaller number given any x,y integer pair.

Why is this ValueError: too many values to unpack (expected 2)

Hi @hanqi

In this case, the condition applies only to the variable x. And it tries to unpack the tuple (x, (x, y)) with else. The correct entry will be made.
(x, y) = (y, x) if y > x else (x, y)
And in order for x to always be a smaller number, you must have a different condition
(x, y) = (y, x) if y < x else (x, y)

2 Likes