Skip to content Skip to sidebar Skip to footer

Unpacking Variable Length List Returned From Function

Ok so I'm defining a function that takes a variable number of inputs and clamps each of them def clamp(*args): return [ max(min(arg, 0.8), 0.2) for arg in args] I like the rea

Solution 1:

I'm not very conviced but here is an alternative solution

>>> clam = lambda a: max(min(a, 0.8), 0.2)

>>> def clamp(a, *args):
...     if args:
...        return [ clam(arg) for arg in (a,)+args]
...     else:
...        return clam(a)
... 
>>> clamp(123, 123)
[0.8, 0.8]
>>> clamp(123)
0.8

Solution 2:

You can force it to unpack a single element by adding a comma after the name. Not ideal but here you go:

A, = clamp(a)

Solution 3:

def clamp(*args):
    lst = [max(min(arg, 0.8), 0.2) for arg in args]
    if len(lst)==1:
        return lst[0]
    return lst

Solution 4:

I think when you call it with one element, you can add a , after the name. a, = clamp(1). In this case, you don't have to modify your function and the automatic unpacking still happens.

>>> a, b, c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>> a, = [1]
>>> a
1
>>> 

Solution 5:

def clamp(*args):
    rt = [max(min(arg, 0.8), 0.2) for arg in args]
    return rt if len(rt) > 1 else rt[0]

or else, remember how you make a tuple of one element. Put a comma after A to force unpack for a single variable.

A, = clamp(0.12) # with your old function which always returns list

Post a Comment for "Unpacking Variable Length List Returned From Function"