views:

71

answers:

1

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.

+1  A: 

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.

Roger Pate
Thanks for the response Roger! Great example.
mkelley33

related questions