2

Just for fun and out of curiosity, I devised this way of writing a generator that counts to infinity, at least in principle. Nothing very pythonian. Just playing around.

But obviously with each iteration lis gets longer until something will eventually break.

Are there other (better or worse) ways to achieve the same goal? Please share.

lis = [1]
gen = ((k, lis.append(k+1))[0] for k in lis)

To use it

for j in gen:
    print(j)
Aguy
  • 7,851
  • 5
  • 31
  • 58
  • 2
    `for i in itertools.count(1): print(i)`... ? See [docs](https://docs.python.org/2.7/library/itertools.html#itertools.count) which also contains equivalent Python code... – Jon Clements Jul 10 '16 at 04:50
  • 1
    @TigerhawkT3 not sure that's the best dupe target (I was looking for one) - as it focuses mostly on an infinitely repeating sequence (although one answer does briefly mention `itertools.count`) - not an infinitely incrementing sequence... – Jon Clements Jul 10 '16 at 05:00
  • Why even use a generator if you are going to be holding a list in memory? – juanpa.arrivillaga Jul 10 '16 at 05:29
  • @JonClements - The question just asks for "infinite elements," and `itertools.count()` is the first suggestion in the highest-voted answer. It's not 100% focused on only incrementing sequences to the total exclusion of a static cycle, but I don't think that's a flaw. – TigerhawkT3 Jul 10 '16 at 13:32
  • 1
    @TigerhawkT3 quoting the OP: *I devised this way of writing a generator that counts to infinity* [...] *Are there other (better or worse) ways to achieve the same goal?* I'm taking **count** to be distinct from *infinite iterable*. – Jon Clements Jul 10 '16 at 13:36
  • @JonClements - I meant the question in the linked dup. It just asks for "infinite elements." It's a little more broad than this question's infinite increment, but it includes an answer that mentions `itertools.count()`. The castle is a little bigger, but it holds the right answer. :) – TigerhawkT3 Jul 11 '16 at 00:16

2 Answers2

4

You can use itertools.count:

import itertools

for i in itertools.count(1):
    print(i)

From the docs above this is functionally equivalent to:

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

You can use it like this:

>>> my_generator = count(3, 2)
>>> next(my_generator)
3
>>> next(my_generator)
5
>>> next(my_generator)
7
new name
  • 15,861
  • 19
  • 68
  • 114
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

Just use itertools.count. Here's an example:

>>> from itertools import count
>>> gen = count(0)
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
3
>>> next(gen)
4
>>>
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199