Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
ZhouYang1993 / exp2.py
Created May 28, 2020 16:28
Iterators in Python
my_list = [1, 2, 3, 4, 5]
print(my_list)
# [1, 2, 3, 4, 5]
my_list_iterator = iter(my_list)
print(my_list_iterator)
# <list_iterator object at 0x7f048a4b67f0>
next(my_list_iterator)
# 1
@ZhouYang1993
ZhouYang1993 / isinstance.py
Created May 28, 2020 20:00
Iterators in Python
from collections.abc import Iterable, Iterator
my_list = [1, 2, 3, 4, 5]
my_list_iterator = iter(my_list)
isinstance(my_list,Iterable)
# True
isinstance(my_list,Iterator)
# False
isinstance(my_list_iterator,Iterable)
@ZhouYang1993
ZhouYang1993 / isinstance.py
Created May 28, 2020 20:02
Iterators in Python
from collections.abc import Iterable, Iterator
my_list = [1, 2, 3, 4, 5]
my_list_iterator = iter(my_list)
isinstance(my_list,Iterable)
#True
isinstance(my_list,Iterator)
#False
isinstance(my_list_iterator,Iterable)
#True
@ZhouYang1993
ZhouYang1993 / Fib.py
Created May 28, 2020 20:48
Iterators in Python
from collections.abc import Iterable, Iterator
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
from collections.abc import Iterable, Iterator
def Fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
@ZhouYang1993
ZhouYang1993 / forloop.py
Created May 28, 2020 21:35
Iterators in Python
# convert an Iterable to an Iterator
my_list_iterator = iter(my_list)
while True:
try:
# get the next item
element = next(my_list_iterator)
except StopIteration:
# if StopIteration is raised, stop for loop
break
@ZhouYang1993
ZhouYang1993 / generator.py
Created May 29, 2020 01:16
Generators in Python
my_list = [i for i in range(8)]
my_generator = (i for i in range(8))
print(my_list)
print(my_generator)
# [0, 1, 2, 3, 4, 5, 6, 7]
# <generator object <genexpr> at 0x7f8fc3ec9a40>
def my_generator(maximum):
n = 0
while n < maximum:
n += 1
yield n
return 'Done'
g = my_generator(maximum=5)
@ZhouYang1993
ZhouYang1993 / generatorFunction.py
Last active May 29, 2020 02:12
Generators in Python
def my_generator(maximum):
n = 0
while n < maximum:
yield n
return 'Done'
print(type(my_generator))
# <class 'function'>
print(type(my_generator(5)))
# <class 'generator'>
@ZhouYang1993
ZhouYang1993 / example.py
Created May 29, 2020 02:17
Generators in Python
def example():
print('step 1')
yield 1
print('step 2')
yield 2
print('step 3')
yield 3
g = example()