function taking scalar or list argument

Rocco Moretti roccomoretti at hotpop.com
Tue Aug 24 12:45:36 EDT 2004


beliavsky at aol.com wrote:

> I can define a function that transforms either a scalar or each element in
> a list as follows:
> 
> def twice(x):
>     try:
>         return map(twice,x)
>     except:
>         return 2*x
> 
> print twice(3) # 6
> print twice([1,4,9]) # [2,8,18]
> 
> Is this good style? I intend to define many functions like this and want
> to use the right method. Thanks.

In addition to those options already mentioned, here's another alternative.

def twice(*args):
     retval = [2*x for x in args]
     if len(retval) == 1:
         return retval[0]
     else:
         return retval

print twice() # []
print twice(3) # 6
print twice([1,4,9]) # [1, 4, 9, 1, 4, 9]

#BUT ...
print twice(*[1,4,9]) # [2,8,18]
# Note '*' -^
print twice(1,4,9) # [2,8,18]
# No '[]' --^----^

You can even omit the if ... else, if you don't mind getting a singleton 
list for the one-parameter case. (i.e. twice(3) == [6])



More information about the Python-list mailing list