Infinite for loops possible in Python?

后端 未结 10 2185
误落风尘
误落风尘 2020-12-06 10:39

Is it possible to get an infinite loop in for loop?

My guess is that there can be an infinite for loop in Python. I\'d like to know this for future refe

10条回答
  •  爱一瞬间的悲伤
    2020-12-06 11:17

    Using itertools.count:

    import itertools
    for i in itertools.count():
        pass
    

    In Python3, range() can go much higher, though not to infinity:

    import sys
    for i in range(sys.maxsize**10):  # you could go even higher if you really want but not infinity
        pass
    

    Another way can be

    def to_infinity():
        index=0
        while 1:
            yield index
            index += 1
    
    for i in to_infinity():
        pass
    

提交回复
热议问题