Search code examples
pythoniteratorrangexrange

Portable, memory efficient range() for Python 2.x and Python 3.x


I am aware of the downsides of range in Python 2.x (it creates a list which is inefficient for large ranges) and it's faster iterator counterpart xrange. In Python 3.x however, range is an iterator and xrange is dropped. Is there a way to write these two loops written with Python 2.x and Python 3.x in such a way that the code will be portable and will use iterators?

# Python 2.x
for i in xrange(a_lot):
    use_i_in_someway(i)

# Python 3.x
for i in range(a_lot):
    use_i_in_someway(i)

I am aware that one may do something like

if(platform.python_version_tuple()[0] == '3'):
    xrange = range

but I was thinking for something less hack-ish and not custom-built.


Solution

  • One alternative is to use the Six module, that provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification.