function taking scalar or list argument

Larry Bates lbates at swamisoft.com
Mon Aug 23 15:09:15 EDT 2004


You may want to take a look at isinstance() function.

def twice(x):
    if isinstance(x, list): return map(twice, x)
    if isinstance(x, (int, float, str)): return 2*x
    return None

print twice(3) # 6
print twice([1,4,9]) # [2,8,18]
print twice('*')

HTH,
Larry Bates
Syscon, Inc.

"beliavsky at aol.com" <beliavsky at 127.0.0.1:7501> wrote in message
news:412a2bce$1_1 at 127.0.0.1...
>
> 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.
>
>
>
> ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet
News==----
> http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000
Newsgroups
> ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption
=---





More information about the Python-list mailing list