I understand yield
, but I came to understand that it is a mechanism to investigate what is yield from
and receive the evaluation of the generator.
I wrote flatten with that understanding
def flatten(x):
if hasattr(x, '__iter__') and not isinstance(x, str):
for y in x:
yield from flatten(y)
else:
yield x
If this yield from
is changed to yield
, the generator will simply be returned, so I wonder if they understand each other.
In : ls = [1,2,3,[4,5],[6,[7,8,[9,10,11],12]]]
In : list(flatten(ls))
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
I'm not sure if I can handle it
Recommended Posts