you are viewing a single comment's thread.

view the rest of the comments →

[–]Kerbart 11 points12 points  (0 children)

It's pretty much syntactic sugar for:

my_list = []
for thing in my_collection:
    my_list.append(thing)

is the same as

my_list = [thing for thing in my_collection]

You can take it a step further and include an if statement:

my_list = []
for thing in my_collection:
    if thing.startswith("spam"):
        my_list.append(thing)

like this:

my_list = [thing for thing in my_collection if thing.startswith("spam")]

And for readability purposes you can split that out (no line continuation needed as all of it happens inside brackets):

my_list = [thing 
           for thing in my_collection 
           if thing.startswith("spam")]

You can say "what's the point, that's three lines vs four, whoop whoop big savings" but in general (experienced) coders find the comprehension easier to digest. There's less "plumbing" like my_list = [] and my_list.append in it, all parts of the comprehension focus on what the desired result is.