[Tutor] any(x)
Cameron Simpson
cs at cskk.id.au
Mon Feb 7 22:57:49 EST 2022
On 07Feb2022 22:05, Oliver Haken <Ollie.ha at outlook.com> wrote:
>I have a generator to make an infinite list of numbers
Hmm. Your computer must be _way_ faster than mine :-) Might be better to
call it an unbounded sequence of numbers.
>Code: Select all<https://forums.sourcepython.com/viewtopic.php?t=2663#>
>
> t = 0
>u = []
>def h ():
> while True:
> t = t + 1
> u.append(t)
> yield u
>h ()
As Alan remarked, you would not normally yield "u" (the list), you would
yield each value of "t". The caling code might assemble those into a
list, or otherwise process them.
So:
def h(t=0):
while True:
yield t
t += 1
which would yield numbers starting at 0 (by default) indefinitely.
Your expression "h()" does _not_ run the function. It prepares a
generator to run the function and returns the generator. A generator is
iterable, so you can iterate over the values it yields. For example in a
for-loop. To make it clear:
g = h()
for i in g:
print(i)
prints 0, then 1, etc. Usually you'd do that directly of course:
for i in h():
>But how do I use it?
So here:
Your code:
> z = any(u)
you want:
z = any(h())
since any() can use any iterable, and a generator is an iterable.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list