3

I am using this loop in my python code:

final_fun=[]
for i_base in xrange(n_base):
  final_fun.append(sum(fun[:,i_base])/n_ci)

and I would want to know how I can simplify this loop? If I simplify this loop will my program be faster? In general I know how to simplify this but here I am blocked by the append!

2 Answers 2

8

Use list comprehensions. It's faster and cleaner. The interpreter can be slowed down a lot by the for loop, and there's nothing to lose by simply rearranging the syntax.

See this explanation for more details.

final_fun = [sum(fun[:,i_base])/n_ci for i_base in xrange(n_base)]
4
  • 1
    This can get complicated sometimes its just nice to have a for loop Aug 1, 2012 at 15:30
  • for loops are often slower in python. Especially if you are using multiple for loops, list comprehensions are designed to handle this kind of thing more efficiently. Aug 1, 2012 at 15:31
  • thank you! I tried this at the beginning but with some mistakes!
    – PanAkry
    Aug 1, 2012 at 15:33
  • @RobVolgman they might be slow, but when i open up a module that contains nothing but list comprehensions in every line even nested list comprehensions it makes me want to stab a fool Aug 1, 2012 at 15:34
2

It seems fun is a two-dimensional NumPy array. In this case, you can simplify and speed up the code significantly by completely avoiding the Python loop:

final_fun = fun.sum(axis=0) / n_ci

You will end up with a NumPy array instead of a list, but chances are this is what you want anyway.

1
  • +1. Thank you for being attentive to an already answered question. Aug 1, 2012 at 15:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.