title: Are there better ways to have different actions chosen in a function based on its inputs?
body: <p>I've made a generic function to generate a 2D grid of size x, y, <code>make_grid</code>.</p>
  
  <pre><code>def make_grid(x, y, mode="empty"):
      if mode == "rand":
          def filling():
              return randint(0, 1)
      else:
          def filling():
              return 0
      grid = []
      for r in range(x):
          row = []
          for c in range(y):
              row.append(filling())
          grid.append(row)
      return grid
  </code></pre>
  
  <p>I've set it up to define the <code>filling</code> function based on the input <code>mode</code> so that I don't end up running a bunch of <code>if</code>s being checked unnecessarily over the for loops - the hope is that over a large grid this would save considerable time.</p>
  
  <p>I'm not sure, however, that this would be the most Pythonic way of achieving this - it doesn't feel clean to define functions within functions in this way. Can anyone suggest better (clearer or more efficient) methods? I feel like lambdas might be the right way, but I haven't ever really got comfortable with them... I should, at the least, be able to define functions elsewhere, choose which one should be called before the for loop, and then use it during the for loops, right?</p>
  
  <p>Edit: here's a more minimal example, as I was shamefully lazy at first and didn't bother making a proper one... (I'm leaving the original so that answers still make sense.)</p>
  
  <pre><code>def example(mode=0):
      if mode == 1:
          def action_to_take():
              print("mode1")
      else:
          def action_to_take():
              print("mode_other")
      for r in range(1000):
          for c in range(1000):
              action_to_take()
  </code></pre>
  
  <p>Just imagine that the conditionally defined <code>action_to_take</code> function is complicated enough to warrant this question, and the loop goes round enough times to make questioning the performance of the code reasonable.</p>