-2

I have typically an outer loop with an inner loop in it. Now I would like to modify the code that way that in some situation the outer loop shall not be executed but just the inner loop. There are no data need from outer loop in the inner loop.

for i in list_a:
    # do sth in list_a
    for j in list_b:
       #do sth in list_b

Could this be done in ONE construct or shall i write two different loop constructs like:

if (conditionA):
   for i in list_a:
      # do sth in list_a
      for j in list_b:
         #do sth in list_b

if (conditionB):
    for j in list_b:
       #do sth in list_b

1 Answers1

1

This is exactly what functions are for: So you don't have to repeat yourself.

def inner_loop():
    for j in list_b:
       #do sth in list_b

if (conditionA):
    for i in list_a:
        # do sth in list_a
        inner_loop()

if (conditionB):
    inner_loop()
Aaron N. Brock
  • 4,276
  • 2
  • 25
  • 43
  • 1
    Thx but i need to split in the different conditions and cant handle it in one loop construct with some conditions in it. – Melanie Gerster Apr 09 '18 at 13:25
  • @MelanieGerster I'm sorry, I don't follow. You have two loops that have different functionality, that you want written in the same construct? – Aaron N. Brock Apr 09 '18 at 13:33
  • Ideally yes. i thought there could be a smart unknown function in python which could handle such cases. but if know i will use different constructs. that is fine for me. it has been just a question... – Melanie Gerster Apr 09 '18 at 13:35
  • @MelanieGerster You _can_ achieve that functionality with lambda functions... I'll add another answer that uses that, however, I feel that this correctly answers the question asked. – Aaron N. Brock Apr 09 '18 at 13:46
  • many thanks. i am happy to read it – Melanie Gerster Apr 09 '18 at 13:52
  • @MelanieGerster Unfortunately, this question got put on hold so I cannot add another answer. However, you can take a look at [this gist](https://gist.github.com/AaronNBrock/a28f703f8cd5868d8000182c016807cd) – Aaron N. Brock Apr 09 '18 at 13:54
  • thank you...great...a very good alternative for me..thank you again – Melanie Gerster Apr 09 '18 at 13:57
  • @MelanieGerster To be completely honest, I'm not sure I would suggest doing it that way, defining a `for loop` twice isn't all that big of a deal and the added complexity of a separate function that takes in a function seems unnecessary. However, this of course depends on your use case. – Aaron N. Brock Apr 09 '18 at 14:22