question on list comprehensions
Alex Martelli
aleaxit at yahoo.com
Sun Oct 17 11:13:25 EDT 2004
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.
Alex
More information about the Python-list
mailing list