Skip to main content
3 of 3
Rollback to Revision 1
Mat
  • 2.1k
  • 2
  • 26
  • 31

Loop outside method or method with internal loop?

If I have a list of objects that need to have an operation performed on each, is there a best practice in abstracting the loop or not?

  1. Looping over list and call

     def func(item):
         some_op(item)
         some_other_op(item)
    
     for item in items:
         func(item)
    
  2. Call method and loop internally

     def func(items):
         for item in items:
             some_op(item)
             some_other_op(item)
    
     func(items)
    

Iteration takes place in both, so I think it would come down to compiler settings because of all the calls to func. Other than reducing function calls, I think #2 allows for not re-writing the loop elsewhere if another method needs to call func; it can just pass a container of arbitrary size.

Is there any merit to one over the other?

pstatix
  • 1k
  • 1
  • 13
  • 18