This page looks best with JavaScript enabled

python generator and recursive function

We know that a function with ‘yield’ will become a generator.

1
2
3
def generator_func(inputs):
    for input_ in inputs:
        yield input_
1
2
3
4
5
6
7
8
9
inputs = [
    None,
    range(1),
    ('1-str'),
    ('2-tuple', 3),
    ['4-list', 5],
    {'6-set', '7-set'},
    {'8-dict': None, '9-dict': None, },
]

output

1
2
3
4
5
6
7
8
9
for e in generator_func(inputs):
    print(e)
# None
# range(0, 1)
# 1-str
# ('2-tuple', 3)
# ['4-list', 5]
# {'7-set', '6-set'}
# {'8-dict': None, '9-dict': None}

But when the function is recursive, you should use ‘yield from’ instead.

Make a flatter with ‘yield from’:

1
2
3
4
5
6
def flattener(seq):
    for s in seq:
        if isinstance(s, str) or not hasattr(s, '__iter__'):
            yield s
        else:
            yield from flattener(s)

output

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
for e in flattener(inputs):
    print(e)
# None
# 0
# 1-str
# 2-tuple
# 3
# 4-list
# 5
# 7-set
# 6-set
# 8-dict
# 9-dict