user8201141
user8201141

Reputation:

Python: split array into variables

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?

Upvotes: 1

Views: 2654

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113915

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

Upvotes: 8

Reut Sharabani
Reut Sharabani

Reputation: 31339

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

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

Upvotes: 3

Related Questions