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.
views:
71answers:
1
+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
2009-11-19 00:55:44
Thanks for the response Roger! Great example.
mkelley33
2009-11-22 21:09:04