1

I have a function that returns a list. The length of this list is unknown to the caller.

def get_array():
    ret = [1, 2]
    return ret

var1, var2 = get_array()

This sets var1 = 1 and var2 = 2. This works fine with all lists except when the length is less than 2. For example, if the list has length of 1:

 def get_array():
    ret = [1]
    return ret

 var1 = get_array()

This sets var1 to [1], but I want var1 to be 1. Is there a cleaner way to unpack this array without having to check its length?

2
  • 2
    What? You obviously need to know its length to decide how many variables to use on the left-hand side of the assignment. In any case, what's the point? Commented Jul 4, 2017 at 15:18
  • 1
    var1, = get_array() Commented Jul 4, 2017 at 15:19

2 Answers 2

8

If you're using python3, you can use the splatted unpacking syntax to help you out here:

In [113]: a,*b = [1]

In [114]: a
Out[114]: 1

In [115]: b
Out[115]: []

Basically, this lets you unpack get_array()[1:] into b, which will be empty, if get_array() returns a list of size 1

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

Comments

3

Sure, if the size of the resulting list is known, use the same notation:

var1, = [1]  # var1 is set to 1

Comments

Your Answer

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