Accessing Variables from Generator

All other Source.Python topics and issues.
REMsleep100
Junior Member
Posts: 3
Joined: Wed Feb 02, 2022 5:17 pm

Accessing Variables from Generator

Postby REMsleep100 » Wed Feb 02, 2022 6:01 pm

I have a generator to make an infinite list of numbers

Code: Select all

 t = 0
u = []
def h ():
 while True:
  t = t + 1
  u.append(t)
  yield u
h ()


But how do I use it?

Code: Select all

 z = any(u)


Thanks, Oliver
User avatar
Ayuto
Project Leader
Posts: 2193
Joined: Sat Jul 07, 2012 8:17 am
Location: Germany

Re: Accessing Variables from Generator

Postby Ayuto » Thu Feb 03, 2022 2:33 pm

What exactly are you trying to archive?

This is how you can use a generator:

Syntax: Select all

>>> def infinite_generator():
i = 0
while True:
i += 1
yield i


>>> gen = infinite_generator()
>>> print(next(gen))
1
>>> print(next(gen))
2
>>> print(next(gen))
3
Of course, you could also loop over the generator, but that will obviously never end:

Syntax: Select all

for x in infinite_generator():
print(x)
REMsleep100
Junior Member
Posts: 3
Joined: Wed Feb 02, 2022 5:17 pm

Re: Accessing Variables from Generator

Postby REMsleep100 » Wed Feb 09, 2022 10:41 pm

I am attempting to get every set of random Boolean values for each number in the list

1. It should be done with lazy evaluation
2. It should reference itself in the generator
REMsleep100
Junior Member
Posts: 3
Joined: Wed Feb 02, 2022 5:17 pm

Re: Accessing Variables from Generator

Postby REMsleep100 » Fri Feb 11, 2022 9:34 pm

Code: Select all

 def func():
  func.variable = "John"

func()

print(func.variable)


There. Accessing a variable from a function

But how do you do that with a generator?

Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 39 guests