Skip to content Skip to sidebar Skip to footer

How To Create A Function For Recursively Generating Iterating Functions

I currently have a bit of Python code that looks like this: for set_k in data: for tup_j in set_k: for tup_l in tup_j: The problem is, I'd like the number of nested fo

Solution 1:

def nfor(data, n=1):
    if n == 1:
        yield from iter(data)
    else:
        for element in data:
            yield from nfor(element, n=n-1)

Demo:

>>> for i in nfor(['ab', 'c'], n=1):
...     print(i)
...     
ab
c
>>> for i in nfor(['ab', 'c'], n=2):
...     print(i)
...     
a
b
c

Post a Comment for "How To Create A Function For Recursively Generating Iterating Functions"