1

I am trying to create a generator that prints the next number on the list. This is a racket version:

  (require racket/generator)

  (define my-gen
    (generator
     (_)
     (for ([x (list 1 2 3))])
       (yield x)))

)

How it should work:

(my-gen) -> 1
(my-gen) -> 2

I also want to be able to use the function directly without having to initialize it at a specific point, so having the generator be the function that actually returns the result, as opposed to something like this:

l = [1, 2, 3]
def myGen():
    for element in l:
        yield element

g = myGen()
print(next(g))

What is the best way to go about this in python?

Lana
  • 1,124
  • 1
  • 8
  • 17
  • What do you mean without initialising it? You could just use a generator expression - `my_gen = (element for element in l)` but this really isn't necessary as `my_gen = iter(l)` would be sufficient in your example. – AChampion Jan 13 '16 at 03:32
  • That's exactly what I meant actually, since I'm reading from a specific file, and I was trying to have the generator return the next item on the list throughout the whole program. – Lana Jan 13 '16 at 03:36

3 Answers3

2
# Generator expression
(exp for x in iter)

# List comprehension
[exp for x in iter]

Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large.

In above generator will create generator object, to get data you have iterate or filter over it. It may be help you

sathish
  • 149
  • 9
1

Using functools.partial:

>>> import functools
>>> l = [1, 2, 3]
>>> my_gen = functools.partial(next, iter(l))
>>> my_gen()
1
>>> my_gen()
2
>>> my_gen()
3
>>> my_gen()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

Is this what you are looking for?

number = 1
while(number<500 +1):
    print('(my-gen) ->', number)
    number +=1