Assert and Yield

Im a bit too lazy to go searching google for the purpose of these keywords. But can anyone please explain the meaning of the assert keyword and the yield keyword and an example of how it can be used? Any help is appreciated.

assert is useful for debugging. You can use it to sanity check variables during the debugging stage. Basically, the following two are equivalent:

Code:

assert (x == 10)
is the same as:
if __debug__:
if not (x == 10): raise AssertionError

The code above will make sure x == 10, or throw an exception if the value is different from 10. This way, you can make sure that the value of x is set to the value you expect it to be, before the program proceeds further down the line and creates problems elsewhere due to the fact that x was not 10 when you expected it to be.

The nice thing about using assert is that if the internal __debug__ system variable is not set, the assert statements will not be evaluated. Thus, your code runs a bit faster when you turn debug mode off, since the assert statements are skipped. In fact, compiled code might omit all the assert statements from the final executable.

You can skip the temporary list, and return "the next value in the generated sequence", like this:

Code:

def give_me_numbers():
import random
for i in range(3):
yield random.randint(1,10)

Then use it as if it was a list, like this:

Code:

for num in give_me_numbers():
print num

It doesn't matter that give_me_numbers doesn't return a list. It returns a generator...

Code:

>>> give_me_numbers()
<generator object at 0x016E4C88>

and you can use that in your for loop.

'yield' is the keyword needed to do this in a function. Instead of 'return'.

You might wonder what the point is. Well, consider building a list of ten thousand items in a function, returning the list, and then stepping through each item.

1) Calculating a list of 10,000 complicated items might take minutes.
2) Storing all 10,000 at once will take a lot of memory.

Whereas if you used a generator function:

1) Each time the function is called, it only calculates the next item. Then it is returned and used. So there is no single big delay at the start waiting for the list to be built. It could be a lot more even on processor use, and the second part starts happening sooner.

2) The list is never all stored. One item is calculated, returned, used and then ready to clear up. Memory use is much, much lower.