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

Posted by froadie on Stack Overflow See other posts from Stack Overflow or by froadie
Published on 2010-05-17T14:03:18Z Indexed on 2010/05/17 14:10 UTC
Read the original article Hit count: 140

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)

© Stack Overflow or respective owner

Related posts about python

Related posts about list-comprehension