nums = [2, 3, 4, 5]
for n in nums:
print(n)
2 3 4 5
for c in "34343":
print(c)
3 4 3 4 3
for key in {"a":1, "b":2, "c":3}:
print(key)
a b c
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 5)
for item in p:
print(item)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-5af2595ff5db> in <module> ----> 1 for item in p: 2 print(item) TypeError: 'Point' object is not iterable
numitr = iter(nums) # iterator
next(numitr)
2
next(numitr)
3
next(numitr)
4
next(numitr)
5
next(numitr)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-17-64ab3acaa676> in <module> ----> 1 next(numitr) StopIteration:
def squares(nums):
for n in nums:
yield n*n
nums
[2, 3, 4, 5]
nums_sqrs = squares(nums)
nums_sqrs
<generator object squares at 0x7f5695d3f6d0>
next(nums_sqrs)
4
next(nums_sqrs)
9
next(nums_sqrs)
16
next(nums_sqrs)
25
next(nums_sqrs)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-30-308d357d66c7> in <module> ----> 1 next(nums_sqrs) StopIteration:
for s in nums_sqrs:
print(s)
for s in squares(nums):
print(s)
4 9 16 25
def squares(nums):
print("Starting computing squares")
for n in nums:
print(f"Yielding square of {n}")
yield n*n
print(f"I am back to generator")
print("Done..finished everything")
nums_sqrs = squares(nums) # the execution has not started... it is in suspended condition
next(nums_sqrs) # execution starts till first yield statement comes then again suspends
Starting computing squares Yielding square of 2
4
next(nums_sqrs) # execution again starts after yield statement! and continues till next yield statement
I am back to generator Yielding square of 3
9
next(nums_sqrs)
I am back to generator Yielding square of 4
16
next(nums_sqrs)
I am back to generator Yielding square of 5
25
next(nums_sqrs) # when there is no yield statement remaining, it will raise StopIteration Exception
I am back to generator Done..finished everything
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-48-85b0df8b5095> in <module> ----> 1 next(nums_sqrs) # when there is no yield statement remaining, it will raise StopIteration Exception StopIteration:
next(nums_sqrs)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-49-308d357d66c7> in <module> ----> 1 next(nums_sqrs) StopIteration:
def three_steps(x):
print("now starting step 1")
yield 1, x
print("now starting step 2")
yield 2, x
print("now starting step 3")
yield 3, x
print("All steps done..must exit now!")
steps = three_steps("hello")
next(steps)
now starting step 1
(1, 'hello')
next(steps)
now starting step 2
(2, 'hello')
next(steps)
now starting step 3
(3, 'hello')
next(steps)
All steps done..must exit now!
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-55-4c63c7417456> in <module> ----> 1 next(steps) StopIteration:
def countdown(n):
while n>0:
yield n
n -= 1
for i in countdown(5):
print(i)
5 4 3 2 1
import gc
gc.get_stats()
[{'collections': 188, 'collected': 6524, 'uncollectable': 0},
{'collections': 17, 'collected': 1689, 'uncollectable': 0},
{'collections': 1, 'collected': 0, 'uncollectable': 0}]
%%file generator.py
import time
import sys
def squares(n):
nums = list(range(n))
return [i*i for i in nums]
def gsquares(n):
for i in range(n):
yield i*i
if __name__ == "__main__":
if sys.argv[1] == "g":
s = 0
for i in gsquares(int(sys.argv[2])):
s += i
time.sleep(10)
print(s)
else:
sqrs = squares(int(sys.argv[1]))
time.sleep(10)
print(sum(sqrs))
Overwriting generator.py
!python generator.py 10000000
333333283333335000000
import os
def find(root):
for path, dirnames, filenames in os.walk(root):
for f in filenames:
yield os.path.join(path, f)
def take(n, seq):
return [next(seq) for i in range(n)]
def naturals():
y = 1
while True:
yield y
y += 1
x10 = (i*i for i in range(10))
for i in x10:
print(i, end=",")
0,1,4,9,16,25,36,49,64,81,
def squares(seq):
return (i*i for i in seq)
nat = naturals()
nat
<generator object naturals at 0x7f5313296e40>
sqr_nat = squares(nat)
sqr_nat
<generator object squares.<locals>.<genexpr> at 0x7f5313987190>
take(10, sqr_nat)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
take(10, sqr_nat)
[121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
take(10, sqr_nat)
[441, 484, 529, 576, 625, 676, 729, 784, 841, 900]
infinite natural number -> sqauares -> tap (take)
import os
def find(root):
for path, dirnames, filenames in os.walk(root):
for f in filenames:
yield os.path.join(path, f)
def grep(pattern, seq):
return (x for x in seq if pattern in x)
files = find(".")
pyfiles = grep(".py", files)
take(5, pyfiles)
['./bank1.py', './tail.py', './square.py~', './bank0.py', './mymodule.py']
def count(seq):
return sum((1 for i in seq))
files = find("/home/vikrant/programming/explorations/python/")
pyfiles = grep(".py", files)
count(pyfiles)
12374
import os
def find(root):
for path, dirnames, filenames in os.walk(root):
for f in filenames:
yield os.path.join(path, f)
def grep(pattern, seq):
return (x for x in seq if pattern in x)
def readlines(filenames):
for file in filenames:
with open(file) as f:
for line in f:
yield line
files = find(".")
pyfiles = grep(".ipynb", files)
lines = readlines(pyfiles)
count(lines)
92121
files = find(".")
pyfiles = grep(".ipynb", files)
lines = readlines(pyfiles)
functions = grep("def ", lines)
count(functions)
393