Zainuddin Lambak
Zainuddin Lambak

Reputation: 21

multiple return from function in python

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

Upvotes: 0

Views: 205

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43126

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()

Upvotes: 7

Related Questions