Why is there no xrange function in Python3?

后端 未结 6 1117
广开言路
广开言路 2020-11-28 00:46

Recently I started using Python3 and it\'s lack of xrange hurts.

Simple example:

1) Python2:

from time import time as t
def          


        
6条回答
  •  半阙折子戏
    2020-11-28 01:31

    Python 3's range type works just like Python 2's xrange. I'm not sure why you're seeing a slowdown, since the iterator returned by your xrange function is exactly what you'd get if you iterated over range directly.

    I'm not able to reproduce the slowdown on my system. Here's how I tested:

    Python 2, with xrange:

    Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> import timeit
    >>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
    18.631936646865853
    

    Python 3, with range is a tiny bit faster:

    Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> import timeit
    >>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
    17.31399508687869
    

    I recently learned that Python 3's range type has some other neat features, such as support for slicing: range(10,100,2)[5:25:5] is range(20, 60, 10)!

提交回复
热议问题