In [2]:
sum(i for i in range(10))
Out[2]:
In [3]:
set(i for i in range(10))
Out[3]:
In [5]:
[i for i in range(10)]
Out[5]:
In [6]:
list(i for i in range(10))
Out[6]:
In [7]:
{i for i in range(10)}
Out[7]:
Must use ()
to get a generator.
Exception is raised without ()
.
In [3]:
# this is NOT tuple!!!
(i for i in range(10))
Out[3]:
In [1]:
i for i in range(10)
In [19]:
import itertools as it
def fibonacci(x1, x2):
while True:
yield x1
x1, x2 = x2, x1 + x2
fiter = fibonacci(1, 1)
list(it.islice(fiter, 0, 10))
Out[19]:
In [23]:
fiter = fibonacci(1, 1)
list(it.takewhile(lambda x: x < 100, fiter))
Out[23]:
Comment¶
yield
cannot be used recursively.
Do NOT use iterator to mimic generator as iterator is not lazy evaluation.
In [28]:
def fib2(x1, x2):
yield x1
return fibonacci(x2, x1 + x2)
In [29]:
fiter2 = fib2(1, 1)
list(it.islice(fiter2, 0, 10))
Out[29]:
In [34]:
import itertools as it
def fib3(x1, x2):
it.chain([x1], fib3(x2, x1 + x2))
In [35]:
fib3(1, 1)