Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is it better to use list comprehensions or for-each loops?

Which of the following is better to use and why?

Method 1:

for k, v in os.environ.items():        print "%s=%s" % (k, v) 

Method 2:

print "\n".join(["%s=%s" % (k, v)     for k,v in os.environ.items()]) 

I tend to lead towards the first as more understandable, but that might just be because I'm new to Python and list comprehensions are still somewhat foreign to me. Is the second way considered more Pythonic? I'm assuming there's no performance difference, but I may be wrong. What would be the advantages and disadvantages of these 2 techniques?

(Code taken from Dive into Python)

like image 241
froadie Avatar asked May 17 '10 14:05

froadie


People also ask

Are list comprehensions better than for loops?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

Why might you use a list comprehension instead of a loop in Python?

List comprehensions are faster than loops in general. It achieves to be faster by loading the entire list into the memory.

Should you use list comprehensions?

List comprehensions are useful and can help you write elegant code that's easy to read and debug, but they're not the right choice for all circumstances. They might make your code run more slowly or use more memory.

Should you use list comprehension in Python?

There are many reasons why Python developers favor list comprehension over loops. The main reason is that it is more efficient. When you use list comprehension instead of loops, you can create a list with far less effort and code. List comprehension saves time because it requires fewer lines of code than loops.


1 Answers

If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer.

If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.

like image 86
Steven D. Majewski Avatar answered Sep 23 '22 20:09

Steven D. Majewski