Question

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.

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top