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?

1
  • 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. Commented Mar 1, 2018 at 22:28

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

Note that the yield from syntax is Python 3 only.
Is it really worth noting a 5+ years old feature of the language any more?
Python 3.3 to be exact @BrendanAbel.
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.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.