Just #python things. They should be called "List Incomprehensions"

@payne747
I understand that list comprehensions (and their relatives, like generator expressions) are a part of Python syntax that usually have no equivalent in other languages.

But once they are understood (which may be hard if one try by just staring at them, with no resort to documentation or a tutor), they are quite handy.

Please, feel free to ask if you need anything related to their syntax,

#Python : You are welcome!

@gwidion I would love an ELI5

@payne747 @gwidion

say you have a loop that fills a output list with results of some operation from an input list:

results = []
for item in things:
compute something using item
results.append(result)

there is a more direct way to represent that, by describing what the content of your result list will be, for each item

if you move the things around a bit for you can get

results = [ compute something using item for item in things ]

@payne747 @gwidion
there is a part about what to do with the item, before the "for", the expression, and one the for to say on what you iterate.

It gets a bit more complicated when you want to iterate on multiple levels, like.

for list_item in …:
for sub_item in list_item:
results.append(some expression using sub_item)

the thing to remember is the order of loops doesn’t change, so it becomes:

[
expression
for list_item in something
for sub_item in list_item
]

@payne747 @gwidion

list comprehensions produce a list, generators are similar but with () instead of [], and they are lazy, content is produced as you consume (iterate on) them, and you can only read a generator once.

set comprehensions produce a set, instead of a list

{expression using a for a in something}

dict comprehensions produce a dict

{key: value for …}

key and value being also expressions that can use the thing you iterate on.

@tshirtman @gwidion

"results = [ compute something using item for item in things ]" -- that's a great way to put it, thank you!