range question, compared to Smalltalk

Tim Peters tim.one at comcast.net
Tue Aug 27 23:18:07 CEST 2002

[Frank Buss]
> I'm a Python newbie, so forgive me, if I'm asking stupid questions :-)
> If I write this:
> import random
> random.choice(range(0, 100000000))

Python's range(i, j) always builds an explicit list with max(0, j-i)

> it took very long to calculate a random number (I know, I can use
> "random.randint(0, 1000000000)").

random.randrange(1000000000) would be best.

> Looks like "range" returns a normal list.


> Why not an object?

A list is an object.

> If I write this in Smalltalk:
> (0 to: 1000000000000) at: 12345678901
> I get the result immediately. If I write "range(0, 1000000000)" in Python
> I'll get a Memory Error.

So don't do that in Python.

> Another question: How can I generate very high random numbers? If I write
> "random.randint(0L, 100000000000000L)" I'll get an overflow error.

Working with unbounded ints often requires entirely different algorithms.
Here's one way people have found useful for generating random huge ints:


> I thought everything is an object

That's so, yes.

> and I can use small and long integers as I want.

You can *try* to, sure.  Some operations have limits, though, and some
algorithms have limitations.  You're not going to have much luck with

    s = 'x' * 100000000000000000000000000000000000

either <wink>.

More information about the Python-list mailing list