+ 1

Can the range() function in python be used to make an infinite range? If yes, how?

I want to create a range from 0 to infinity. How can I do it with range(), or please tell some other way by which it can be done.

6th Aug 2018, 5:00 PM
Nandita Biswas
Nandita Biswas - avatar
2 Réponses
+ 4
No, range() can't. But itertools.count() can. For your problem, you could do from itertools import count for i in count(): do_something_with(i) You can also specify from which number you want it to start counting and by how many steps you want it to increment each time. For example, to get all odd numbers, just use count(1, 2). Full documentation here: https://docs.python.org/3/library/itertools.html#itertools.count
6th Aug 2018, 5:12 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
you can do really high numbers with range. if you just want an "infinite" counter you can do: a = 0 while True: print(a) a += 1
6th Aug 2018, 5:19 PM
Markus Kaleton
Markus Kaleton - avatar