In [13]:
%pprint

Pretty printing has been turned OFF

In [14]:
from random import sample

In [15]:
# Iterator

In [16]:
def test_yield():
n = 100
k = 50
nums = sample(range(n), k=k)
print(f"Sampled {k} numbers: {nums}")

for i in nums:
yield i

In [17]:
test_yield()

Out[17]:
<generator object test_yield at 0x1037ee200>
In [18]:
it = test_yield()

In [19]:
it

Out[19]:
<generator object test_yield at 0x1037ee580>
In [20]:
next(it)

Sampled 50 numbers: [39, 17, 36, 84, 9, 21, 60, 97, 5, 15, 35, 83, 11, 79, 94, 31, 41, 52, 80, 25, 78, 48, 61, 42, 1, 92, 67, 29, 59, 98, 28, 85, 23, 88, 16, 45, 56, 90, 32, 6, 87, 99, 22, 19, 46, 50, 55, 64, 40, 63]

Out[20]:
39
In [21]:
next(it)

Out[21]:
17
In [22]:
next(it)

Out[22]:
36
In [23]:
list(it)

Out[23]:
[84, 9, 21, 60, 97, 5, 15, 35, 83, 11, 79, 94, 31, 41, 52, 80, 25, 78, 48, 61, 42, 1, 92, 67, 29, 59, 98, 28, 85, 23, 88, 16, 45, 56, 90, 32, 6, 87, 99, 22, 19, 46, 50, 55, 64, 40, 63]
In [12]:
for n in it:
print(n)

In [24]:
next(it)

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-24-bc1ab118995a> in <module>
----> 1 next(it)

StopIteration: 
In [25]:
it = test_yield()

In [26]:
for n in it:
print(n, end=" ")

Sampled 50 numbers: [95, 65, 3, 37, 94, 53, 59, 99, 23, 56, 43, 86, 12, 5, 15, 74, 77, 83, 49, 61, 18, 36, 13, 17, 22, 87, 63, 30, 7, 38, 2, 32, 27, 91, 48, 45, 46, 50, 52, 92, 66, 70, 42, 20, 14, 69, 84, 79, 33, 62]
95 65 3 37 94 53 59 99 23 56 43 86 12 5 15 74 77 83 49 61 18 36 13 17 22 87 63 30 7 38 2 32 27 91 48 45 46 50 52 92 66 70 42 20 14 69 84 79 33 62