python list comprehension double for -


vec = [[1,2,3], [4,5,6], [7,8,9]] print [num elem in vec num in elem]      <-----  >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] 

this tricking me out.
understand elem lists inside of list for elem in vic
don't quite understand usage of num , for num in elem in beginning , end.

how python interpret this?
what's order looks at?

lets break down.

a simple list-comprehension:

[x x in collection] 

this easy understand if break parts: [a b in c]

  • a item in resulting list
  • b each item in collection c
  • c collection itself.

in way, 1 write:

[x.lower() x in words] 

in order convert words in list lowercase.


it when complicate list so:

[x y in collection x in y] # [a b in c d in e] 

here, special happens. want our final list include a items, , a items found inside b items, have tell list-comprehension that.

  • a item in resulting list
  • b each item in collection c
  • c collection itself
  • d each item in collection e (in case, a)
  • e collection (in case, b)

this logic similar normal loop:

for y in collection:     #      b in c:     x in y:          #          d in e: (in case: in b)         # receive x      #              # receive 

to expand on this, , give great example + explanation, imagine there train.

the train engine (the front) going there (the result of list-comprehension)

then, there number of train cars, each train car in form: for x in y

a list comprehension this:

[z b in c in b d in c ... z in y] 

which having regular for-loop:

for b in a:     c in b:         d in c:             ...                 z in y:                     # have z 

in other words, instead of going down line , indenting, in list-comprehension add next loop on end.

to go train analogy:

engine - car - car - car ... tail

what tail? tail special thing in list-comprehensions. don't need one, if have tail, tail condition, @ example:

[line line in file if not line.startswith('#')]  

this give every line in file long line didn't start hashtag (#), others skipped.

the trick using "tail" of train is checked true/false @ same time have final 'engine' or 'result' loops, above example in regular for-loop this:

for line in file:     if not line.startswith('#'):         # have line 

please note: though in analogy of train there 'tail' @ end of train, condition or 'tail' can after every 'car' or loop...

for example:

>>> z = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] >>> [x y in z if sum(y)>10 x in y if x < 10] [5, 6, 7, 8, 9] 

in regular for-loop:

>>> y in z:     if sum(y)>10:         x in y:             if x < 10:                 print x  5 6 7 8 9 

Comments