[New-bugs-announce] [issue3508] range() is not a generator when used in for's

Diego report at bugs.python.org
Wed Aug 6 06:25:32 CEST 2008


New submission from Diego <jacobidiego at gmail.com>:

Hi.

I am a debian lenny user so i am still using python 2.5 so i dont know 
how is this "bug" working on newer pythons. Please close it if you find 
that it doesnt exists.

It may not be a bug but.

I have maked an script to optimice minterms sums (This is electronics 
stuff to reduce the number of logic devices in an electronic design).
The algorithm depends exponentially on the number of bits in the input 
and the output. So to test it i have to generate 2**N_input_bits 
strings in a list. Each string being of N_input_bits+N_output_bits long.

The problem starts when N_input_bits is too much long. (from 25 and up)
The function range(2**N_input_bits) instantiates a list with all thoose 
numbers.

I have maked a test script to check it out:

import time

N=32

try:
  range(2**N)
  # range(): allocates N's integer's items in a list
except Exception, error:
  print "ERROR: ",error, "   Items=",N
  print

time.sleep(10)

def RANGE(a):
  # GENERATOR: Creates one output eachtime it is called.
  i=0
  while i<a:
    yield i
    i=i+1
  return

try:
  for x in RANGE(2**N):
    if not x%100:
      print x
except Exception, error:
  print "ERROR: ",error, "   Items=",N
  print
      

If i am not mistaken, "RANGE" will only take up one integer of memory 
each time instead of a complete list with "range()".
So it is better to use RANGE (a generator) with for's when i do not 
need to edit the list.
I think that range is mostly used in for's, so it will be a big improve 
to make the line:

for ... in range(....):

as a generator behavior and the normal range use:

alist = range(50)

as the same list.

This for line is very common in many programs and the content of the 
list can not be edited inside the for, it is only used by the for.
So, it can speed up python a little without requiring any changes.


Please if you consider this i not a bug or suggestion, or what ever, 
just close/delete/ignore the post. :)

Cheers.
Diego.

----------
messages: 70769
nosy: epsilon_da
severity: normal
status: open
title: range() is not a generator when used in for's
versions: Python 2.5

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue3508>
_______________________________________


More information about the New-bugs-announce mailing list