0
def example():
    var1 = {'a':1,'b':2}
    var2 = {'c':3,'d':4}

    return var1,var2

[v1, v2] = example()

I want to assign var1 to v1, and var2 to v2. Is it ok for me to unpacked tuple var1,var2 into list v1,v2. So far, I haven't found anyone unpack the multiple return value into list

2

1 Answer 1

7

Semantically, there is no difference between unpacking into a list or a tuple. All of these are equivalent:

v1, v2 = example()
(v1, v2) = example()
[v1, v2] = example()

(See also the assignment statement grammar.)

However, unpacking into a list is a relatively unknown feature, so it might be confusing for people who read your code. It's also needlessly verbose. That's why I would strongly recommend using the well-known unpacking syntax without any parentheses or brackets:

v1, v2 = example()
Sign up to request clarification or add additional context in comments.

1 Comment

yep bytcode is identical for all 3, e.g. dis.dis('[v1, v2] = example()')

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.