len() should always return something

Terry Reedy tjreedy at udel.edu
Fri Jul 24 20:52:38 CEST 2009


Phillip M. Feldman wrote:

> I've been converting Matlab codes to Python.  In Matlab, a scalar is 
> just a one-by-one matrix and has a length of 1.  This convention seems 
> no less arbitrary to me than Python's convention that the concept of 
> length is not applicable to ints and floats.

Multiplication of a vector/matrix by a scalar always defined and 
commutative. Multiplication of a vector/matrix by a 1x1 matrix is not 
always even defined. So not having scalars in a matrix package strikes 
me as a bit odd.

 > My workaround was to write
> the following function:
> 
> def is_scalar(x):
>    """Return True if x is an instance of int, float, or complex.
>    Otherwise, return False.  Note: If x is a length-1 list or array
>    containing an int, float, or complex value, False is returned."""
>    if isinstance(x,int) or isinstance(x,float) or isinstance(x,complex):

Better:    if isinstance(x, (int, float, complex)):

but you forgot decimals and fractions and any other possible number modules.

In 3.1,
 >>> from numbers import Number
 >>> from decimal import Decimal
 >>> from fractions import Fraction
 >>> for x in 1, 1.0, (1+0j), Decimal(1), Fraction(1,1):
	isinstance(x, Number)

	
True
True
True
True
True

and the same for any other module that registers a class as a Number

>       return True
>    return False
> 
> The application is the following: In various types of scientific 
> applications, one operates on a list of measurements.  If there is only 
> a single measurement, it is reasonable to allow the calling program to 
> pass a scalar without wrapping it up into a list or array.

If you want to do that, start with

def f(x):
   try: len(x)
   except TypeError: x = x,

or in 3.1 use Number test above.

Terry Jan Reedy




More information about the Python-list mailing list