+ 5
How it works?
def is_Even(k): if not k % 2: print(f'{k}-even', end=' ') yield else: print(f'{k}-odd', end=' ') evens = [k for k in range(10) for bar in is_Even(k)] print(f'\n{evens=}') Can you figure out how the preceding produces these results? 0-even 1-odd 2-even 3-odd 4-even 5-odd 6-even 7-odd 8-even 9-odd evens=[0, 2, 4, 6, 8] In particular, what does for bar in is_Even(k) do in the list comprehension? https://code.sololearn.com/ct6LM6vHhg6G/?ref=app
2 Answers
+ 5
Python implement predicates features . They mayĀ succeedĀ orĀ fail. To succeed/fail means that the system was/was'nt able to establish that the predicate holds given the information available.
Success or failure is implemented in Python through generators. A generator thatĀ yields a result is said to succeed one that does notĀ yieldĀ a result, fails.
In this case,Ā is_Even(k)Ā succeeds/fails whenĀ kĀ is even/odd. (In either case it produces an output line.) When
for bar in is_Even(k)
succeeds/fails for a givenĀ k, the list comprehension completes/fails to complete the iteration for thatĀ kĀ and includes/does'nt includeĀ kĀ in the generated list.
+ 2
To masterĀ yield, you must understand thatĀ when you call the function, the code you have written in the function body does not run.Ā The function only returns the generator object, this is a bit tricky :-)
Then, your code will continue from where it left off each timeĀ forĀ uses the generator.
Now the hard part:
The first time theĀ forĀ calls the generator object created from your function, it will run the code in your function from the beginning until it hitsĀ yield, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hittingĀ yield. That can be because the loop has come to an end, or because you no longer satisfy anĀ "if/else".
This might help...
https://stackoverflow.com/questions/7362900/behaviour-of-pythons-yield
https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do