[Tutor] List comprehension question
Alan Gauld
alan.gauld at btinternet.com
Mon Nov 8 19:29:56 CET 2010
"Stefan Behnel" <stefan_ml at behnel.de> wrote
>> Why use math.sqrt() instead of just using the ** operator?
>>
>> return sum(x for x in range(1, int(n**0.5)) if n%x == 0)
>>
> Since this operation is only evaluated once in the whole runtime of
> the loop, I think readability beats the likely very tiny performance
> difference here.
Ah, I wondered if readability was the reason. I hadn't thought about
it hard enough to notice the sqrt() would only be called once! :-)
As to readability I personally prefer the exponentiation sign (or even
pow()!)
and don't think I have ever used math.sqrt() in my 12 years of Python.
But I recognise that some may prefer sqrt, especially if they don't
have a math background.
Alan G.
More information about the Tutor
mailing list