DEV Community

Discussion on: Things that weren't so obvious when you started to program in Python

Collapse
 
skyxie_60 profile image
skyxie

I could never understand why pythonistas (is that the right term?) like list comprehension. It seems much more confusing to me than the functional map pattern. And aside from sum, there aren't great patterns for reduce or fold!

Collapse
 
rascalking profile image
David Bonner

Think of it as a gateway to functional programming. It mostly looks like a compact version of a for loop, so it's easier for folks who only know procedural or oo.

Collapse
 
winstonyallow profile image
Winston • Edited

I think list comprehensions feel more pythonic. The syntax fits perfectly with the rest of python. I also think it is more similar to natural languages.

Example:

dog.name for dog in animals if dog.type == "dog"

"Please give me the dog names for every dog from my animals (if it really is a dog)"

It is also easy to use the same syntax for dictionary comprehensions and generators. Especially generators are a useful concept. Instead of creating a new list in memory they can generate them on the fly:

websites = (download(url) for url in the_complete_internet)

for page in websites:
    print(page)

Instead of downloading the complete internet into your memory this will download the pages one by one while iterating the generator.

These are the reasons why I personally love the comprehension syntax in python.

Edit
Uhm I just noted that your comment is already a year old. Sorry for reviving an old conversation.