len() should always return something

Terry Reedy tjreedy at udel.edu
Fri Jul 24 16:52:53 EDT 2009

Chris Rebert wrote:

> I think the point made by Grant Edwards is instructive. len(x) = 1
> typically implies list(x)[0] and similar should be valid. 

At least, one should be able to iterate with x and get len(x) items.
See below.

>> And there's nothing ambiguous about len(42).
> Really? What is its value then? I think arguments of varying quality
> can be made for:
> 1 - as the OP and those from array programming languages would suggest
> 2 - the number of decimal digits in 42, if one was feeling Perlish
> 6 - the minimum number of bits necessary to represent 42 in binary
> 32 (or 64, depending on your CPU) - the number of bits necessary to
> represent an int (obviously breaks down a bit with arbitrary-magnitude
> ints)
> undefined - i.e. it causes an error, the current behavior; asking for
> the length of a non-collection is "nonsensical" or "absurd"

In set theory, one can define counts recursively as follows
0 = {} (set, not dict)
n+1 = n | {n}
so len(n) = n, and in particular, len(42) = 42.

On the same basis, it has been proposed (and rejected) that iter(n) == 
range(n), do that we could write 'for i in 10' for instance. Guido 
thought this too esoteric.

Terry Jan Reedy

More information about the Python-list mailing list