Search code examples
list-comprehensionpython-2.6python-2.5

What are the advantage and disadvantages of using a list comprehension in Python 2.54-6?


I've heard that list comprehensions can be slow sometimes, but I'm not sure why? I'm new to Python (coming from a C# background), and I'd like to know more about when to use a list comprehension versus a for loop. Any ideas, suggestions, advice, or examples? Thanks for all the help.


Solution

  • Use a list comprehension (LC) when it's appropriate.

    For example, if you are passing any ol' iterable to a function, a generator expression (genexpr) is often more appropriate, and a LC is wasteful:

    "".join([str(n) for n in xrange(10)])
    # becomes
    "".join(str(n) for n in xrange(10))
    

    Or, if you don't need a full list, a for-loop with a break statement would be your choice. The itertools module also has tools, such as takewhile.