question on list comprehensions

Bengt Richter bokr at oz.net
Sun Oct 17 17:42:36 EDT 2004


On Sun, 17 Oct 2004 17:13:25 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>Mustafa Demirhan <mustafademirhan at gmail.com> wrote:
>
>> Why not just use while loops instead of for loops? You dont have to
>> create a new array each time you want a loop - you can simply use an
>> index integer.
>> 
>>     i = 0
>>     while i < 5000000:
>>         res [0] = res [0] + i
>>         i = i + 1
>> 
>> Takes less than 2 seconds on my laptop.
>
>Sure, this is fine, but low-level twiddling with indices isn't all that
>nice.  A compact alternative such as
>
>    res[0] = sum(xrange(5000000))
>
>is, IMHO, preferable to your while loop, not so much because it may be
>faster, but because it expresses a single design idea ("let's sum the
>first 5 million nonnegative integers") very directly, rather than
>getting into the low-level implementation details of _how_ we generate
>those integers one after the other, and how we sum them up ditto.
>
As I'm sure you know, sum(xrange(n)) is pretty predictable:

 >>> for n in xrange(10):
 ...     print n, sum(xrange(n)), n*(n-1)/2
 ...
 0 0 0
 1 0 0
 2 1 1
 3 3 3
 4 6 6
 5 10 10
 6 15 15
 7 21 21
 8 28 28
 9 36 36
 >>> n=5000000; print n, sum(xrange(n)), n*(n-1)/2
 5000000 12499997500000 12499997500000

Guess where the time and space was consumed ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list