whi
whi

Reputation: 2750

What is the best way to return items in Python that meet a specific condition

The code I'm currently using is:

def f(*args):
    lst=[str(i) for i in args]
    if len(lst)==1:lst = lst[0]
    return lst

What I would like is:

a=f(1) #'1', not [1]

a,b = f(1,2) #'1', '2'

Only one argument would be a list, which would be represented by a.

What alternative exists aside from using an if statement?

Upvotes: 1

Views: 86

Answers (4)

Takahiro
Takahiro

Reputation: 1262

I suggest to use yield:

def f(*args):
    for i in args:
        yield str(i)

a, = f(1)
print a
a, b = f(1, 2)
print a, b

which returns:

1
1 2

is it what you want?

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304355

Returning different types like that can be confusing. I'd recommend using

a = f(1)[0]

or

[a] = f(1)

or

a, = f(1)

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251428

If I understand you correctly, no. If you accept variable arguments with *args, then you get a list, even if there is only one argument.

You could of course separate the first argument with def f(first, *rest), but then you have to do special-casing to combine the elements when you do want a list.

Upvotes: 0

David Robinson
David Robinson

Reputation: 78610

Yes:

return lst[0] if len(lst) == 1 else lst

Upvotes: 1

Related Questions