Search code examples
pythonperformancememory-efficient

How to make simple for-loop consuming less memory?


def odd():
    for i in xrange(0, 100):
        if i % 2 == 1:
            print i

I have this small function. I would like to know:

  1. If there is a way to make it consume less memory?
  2. What are the tools and techniques you can use to efficiently measure and improve memory consumption?

I have this question in mind after looking at the following question: odd numbers


Solution

  • There is a recent answer on Stackoverflow about memory consumption measurement.

    As for the memory consumption of your loop, it is negligible, and does not depend on the upper bound of the range, since xrange() does not really store much more than the next value it will return.