0

Why does the following code produce the result? The LHS and RHS structure is different yet,this is the result..

[[w,x],[[y],z]]=[{10,20},[(30,),40]]

w

10

x

20

y

30

z

40

1 Answer 1

1

It's actually not guaranteed that w and x will always produce the same result, in dependence of your Python interpreter. Try switching it to:

>>> [[w,x],[[y],z]]=[{20,10},[(30,),40]]
>>> w
10

That's because the first 'entry' is a set and sets are not guaranteed to be ordered. The rest will work pretty much as expected because tuples and lists are ordered. It doesn't matter of the actual type on both sides so long as there is a parity, i.e. (x, y) = [p, q] will work the same as [x, y] = (p, q).

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah,that's what I wanted to know..Is there any specific reason why parity is not required?That's so counterintuitive.
@metasj - when you do assignments this way you're just swapping 'references' - Python doesn't care what container the reference is coming from as long as you provide the same number of elements on both sides to satisfy the basic 'number of assignments on LHS has to match the RHS` rule. So, the parity of elements is required, but you don't need parity of their container types because they get discarded during the assignment anyway. If you're looking for a more specific reason it's probably a mix of a speed optimization (why would you care about the container types?) and a KISS principle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.