language design question
Steven Bethard
steven.bethard at gmail.com
Mon Jul 10 00:38:29 EDT 2006
Terry Reedy wrote:
> "Gregory Guthrie" <guthrie at mum.edu> wrote in message
> news:1152465029_31209 at sp6iad.superfeed.net...
>> - why is len() not a member function of strings? Instead one says
>> len(w).
>
> Consider
>>>> map(len, ('abc', (1,2,3), [1,2], {1:2}))
> [3, 3, 2, 1]
>
> Now try to rewrite this using methods (member functions).
For all the doubters out there, here's an example you can't really
rewrite with a list comprehension::
>>> sorted(['aaa', 'bb', 'c'])
['aaa', 'bb', 'c']
>>> sorted(['aaa', 'bb', 'c'], key=len)
['c', 'bb', 'aaa']
If len() were a method of string objects, you could try using the
unbound method and writing this as::
>>> sorted(['aaa', 'bb', 'c'], key=str.len)
['c', 'bb', 'aaa']
But then your code would break on lists that weren't strings.
STeVe
More information about the Python-list
mailing list