1. 3
  1.  

  2. 2

    List comprehensions. They’re usually faster than equivalent for loops and don’t leave any state hanging around. And they have less LOC. Sometimes map can be faster, depending on what you’re doing (invoking functions is costly either way, so list comprehensions that allow you to remove lambdas are a win).

    Further discussion here http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map

    General loop optimisation, straight from Guido himself: http://www.python.org/doc/essays/list2str.html

    And general tips: http://wiki.python.org/moin/PythonSpeed/PerformanceTips

    1. 1

      And now we have generator expressions, which often provide even further improvements. I believe Python 2.4 and up support them.

      for n in (x ** 2 for x in range(10)):
          do_something(n)