Python 2.7 range Function provokes a Memory Error

Chris Angelico rosuav at gmail.com
Thu Mar 2 06:43:22 EST 2023


On Thu, 2 Mar 2023 at 22:27, Stephen Tucker <stephen_tucker at sil.org> wrote:
>
> Hi,
>
> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
>
> I assume that this is because the function produces a list which it then
> iterates through.
>
> 1. Does the  range  function in Python 3.x behave the same way?

No, but list(range(x)) might, for the same reason. In Py2, range
returns a list, which means it needs a gigantic collection of integer
objects. In Py3, a range object just defines its start/stop/step, but
if you call list() on it, you get the same sort of

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?
>
> To get round the problem I have written my own software that is used in a
> for  loop.

xrange is an iterator in Py2, so that's the easiest way to handle it.
Obviously migrating to Py3 would be the best way, but in the meantime,
xrange will probably do what you need.

ChrisA


More information about the Python-list mailing list