6

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 for statements to differ based on user input. If I wanted to create a function which generated n number of for statements like those above, how might I go about doing that?

Daniel
  • 159
  • 1
  • 3
  • 9
  • You could seperate the loop into a function, then you could recursively call the function. Exactly how it would work though would depend on the use case. – Carcigenicate Mar 01 '18 at 22:28

1 Answers1

8
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
wim
  • 338,267
  • 99
  • 616
  • 750
  • 3
    Note that the `yield from` syntax is Python 3 only. – Brendan Abel Mar 01 '18 at 22:34
  • 3
    Is it really worth noting a 5+ years old feature of the language any more? – wim Mar 01 '18 at 22:37
  • [Python 3.3](https://www.python.org/dev/peps/pep-0380/) to be exact @BrendanAbel. – Christian Dean Mar 01 '18 at 22:37
  • 3
    Eh, I think many people still use Python 2 for legacy code @wim. OTHO, I think you do have a point. If people still haven't ported to Python 3 by now, that's not really your problem. – Christian Dean Mar 01 '18 at 22:39
  • 1
    Unless the OP specified a lower Python version, these kind of comments are just litter. Python 2 EOL is < 2 years. – wim Mar 01 '18 at 22:40
  • Yeah, I know Python's ending support for Python 2 in 2020. Like I said, there are still people out their who for one reason or another haven't ported their legacy code to Python 3. _In my opinion_, and Given SO's popularity, _I would_ note that code in my uses certain Python 3 features. But I do understand where you're coming from. – Christian Dean Mar 01 '18 at 22:44
  • @wim Yeah, I may be a bit influenced by the fact that I work in an industry that is still almost completely Python2. I'd say it's still widely used enough that it's worth at least a *mention*. – Brendan Abel Mar 01 '18 at 22:49