Minimum and Maximum of a list containing floating point numbers

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Sep 7 05:50:41 CEST 2010


On Tue, 07 Sep 2010 12:40:57 +1000, Ben Finney wrote:

> Steven D'Aprano <steve-REMOVE-THIS at cybersource.com.au> writes:
> 
>> On Tue, 07 Sep 2010 11:00:45 +1000, Ben Finney wrote:
>>
>> > If you're going to use the list of float objects, you can convert
>> > them all with a list comprehension.
>> [...]
>> >     >>> numbers_as_float = [float(x) for x in numbers_as_str]
>>
>> That's awfully verbose. A map is simpler:
>>
>> numbers_as_float = map(float, numbers_as_str)
> 
> I'll pay “verbose”, but not “awfully”. There is little difference in
> verbosity between your example and mine. Further, I don't see my example
> as excessive, which I assume your “awfully” entails.

Sorry, verbose is not the word I want... I don't know what word I 
*actually* want, so let me explain.

Instead of thinking about a single transformation "change a list of 
strings to a list of floats", the list comp form forces you to think 
about the individual list items and the mechanics of looping, and reduces 
lists to a second-class data type: we can operate on ints without caring 
about individual bits, but we can't operate on lists without caring about 
individual list items.

Why do I need to care about individual items? The list comp even gives 
them a name, "x" in your example, even though that name isn't used 
anywhere else. Why do I need to specify that walking the list must be 
done from left-to-right rather than whatever order the compiler thinks 
best, or even in parallel?

Answer: I don't, and shouldn't need to. With map, such internal details 
of how the transformation is performed is hidden. I shouldn't need to 
specify *how* to convert a list of strings to a list of floats. While a 
list comp is less verbose than a for-loop, which is less again than a 
while-loop, they all specify how to do the transformation, which is 
mental overhead I shouldn't need to care about.

Of course, list comps are so seductively easy, and functional programming 
so conceptually different from what many people are used to, that such 
over-specification is an awfully easy trap to fall into. I'm sure my own 
code is filled with similar examples where I use a list comp where a map 
is more suitable.


-- 
Steven



More information about the Python-list mailing list