[Tutor] Writing a prime number program using upper bound of square root of n

Steven D'Aprano steve at pearwood.info
Mon Aug 23 02:53:03 CEST 2010


On Mon, 23 Aug 2010 07:48:03 am Denis Gomes wrote:
> Nick,
>
>    If you are using python 2.X, xrange(2,n) is just like range(2,n),
> the xrange function is faster.  In python 3.X, they got rid of the
> slower range function and renamed xrange to range.

A slight over-simplification, but broadly correct.

> The x in [x for x 
> in xrange...] will just go from 2 to the number n, but not including
> n.  


I see people using list comprehensions like this:

[x for x in xrange(20)]  # for example

quite frequently. I've even done it myself. But it's silly and wasteful. 
That is exactly the same, only slower and more complicated, as:

list(xrange(20))

or

range(20)


Any time you write [x for x in SOMETHING] just drop the list 
comprehension and use SOMETHING on it's own. (You might need to call 
list(SOMETHING), but often you don't.)


-- 
Steven D'Aprano


More information about the Tutor mailing list