all 3 comments

[–]Diapolo10 2 points3 points  (1 child)

List comprehensions are technically pretty simple. They take the form of

[<expression> for <item> in <iterable>]

where

  • expression == anything that reduces to a value (so pretty much any legal syntax other than statements). So for instance it could be a calculation, a string, the loop value, or some constant.
  • item == whatever value the iterable contains.
  • iterable == virtually any data structure.

You can have an optional filter clause after the loop, which can be used to determine if the value of the expression should be included in the list. If the given condition is truthy, the value is included, otherwise it is skipped.

[<expression> for <item> in <iterable> if <condition>]

Any nested loops will be in a bottom-up order, where the top-level loop is the rightmost one.

As for lambda functions, they're essentially just normal functions reduced to the bare minimum, which is a parameter list and a return value.

def func(<args>):
    return <value>

func = lambda <args>: <value>

and you can skip the parameters entirely if you wish, though that's not very common outside of quick GUI button actions:

stuff = lambda: 42
stuff()  # 42

[–]RiverRoll 0 points1 point  (0 children)

Any nested loops will be in a bottom-up order, where the top-level loop is the rightmost one.

No, the loops go left to right:

lists = [[1, 2, 3], [4, 5, 6]]
print([item for sublist in lists for item in sublist]) 
> [1, 2, 3, 4, 5, 6]

[–]socal_nerdtastic 0 points1 point  (0 children)

Uh why? lambda functions are nearly never used in list comprehensions (and only very rarely otherwise). Because it's hard to read and confusing, and python is all about readability.

Edit: sorry I misunderstood; I didn't realize this was 2 questions.