In [ ]:
a = 10
while a > 0:
print(a)
a -= 1
In [ ]:
for a in range(0,10):
print(a)
In [ ]:
[print(a) for a in range(0,10)]
In [35]:
for i in range(0,500):
if i%376==0:
print("Got it!")
break
.... and sometimes the condition changes?
In [39]:
from random import randint
divisor = randint(1,500)
for i in range(1,500):
if i%divisor==0:
print("Got it: " + str(i))
break
It seems we don't need to generate the big list at all. Imagine it took some time, like 0.5 seconds for each element to check. Do we need to have them all before we check?
We need a lazy evaluation, not eager.
In [53]:
# Normal method of using collections - just generate all at once
a = [1,2,3,4,5]
In [54]:
# Let's change the list into an ITERATOR
my_iterator = iter(a)
print(type(my_iterator))
print(my_iterator)
In [55]:
# Let's iterate the iterator
next(my_iterator)
Out[55]:
In [56]:
# And some more:
next(my_iterator)
next(my_iterator)
next(my_iterator)
next(my_iterator)
Out[56]:
In [57]:
# ... and more:
next(my_iterator)
Woops! When iterator is done, it always throws a STOP sign.
A better approach is to just iterate over the iterator.
In [58]:
some_list = [1,2,3,4,5,5]
some_iter = iter(some_list)
for x in some_iter:
print(x)
In [66]:
class lazy_range:
def __init__(self):
self.counter = 0
def __iter__(self):
return self
def __next__(self):
self.counter += 1
return self.counter
In [67]:
# Something like iter(some_list)
my_lazy_range = lazy_range()
next(my_lazy_range)
Out[67]:
In [68]:
for x in lazy_range():
print(x)
if x >10:
break
In [82]:
def laziest_range(N):
i = 0
while i<N:
yield i
i += 1
In [83]:
a = laziest_range(5)
In [84]:
next(a)
Out[84]:
In [85]:
next(a)
Out[85]:
In [86]:
for x in laziest_range(10):
print(x)
In [87]:
laziest_shortest_range = (x for x in range(10))
In [88]:
next(laziest_shortest_range)
Out[88]:
In [89]:
next(laziest_shortest_range)
Out[89]:
In [91]:
a = [x for x in range(0,100000)]
b = (x for x in range(0,100000))
In [94]:
import sys
print(sys.getsizeof(a))
print(sys.getsizeof(b))
In [97]:
def semaphore():
print("You go")
yield
print("No, you go")
yield
print("No, really, you go!")
yield
In [100]:
a = semaphore()
In [104]:
next(a)
In [105]:
next(a)
In [106]:
next(a)
In [114]:
from time import sleep
from random import randint
def get_latest_customers():
rv = []
for i in range(10):
sleep(.5)
rv.append(randint(1,20))
return rv
customer_id = 18
In [115]:
# We gather lot's of customer ID's and then check if our customer ID=19 is there.
print(customer_id in get_latest_customers())
In [117]:
def get_latest_customers_lazy(n):
for i in range(n):
sleep(.5)
yield(randint(1,20))
In [118]:
iterator = get_latest_customers_lazy(2000000000)
In [120]:
for x in iterator:
if customer_id is x:
print("Found him!")
break
else:
print("Still looking..." + str(x))
In [ ]: