3 ms·
I ran a quick test to see what's going on: >>> state = [1, 2, 3] >>> states = [4, 5, 6] >>> [st for s in state for st in states] [4, 5, 6, 4, 5
by llambda 15y ago
I ran a quick test to see what's going on:
>>> state = [1, 2, 3]
>>> states = [4, 5, 6]
>>> [st for s in state for st in states]
[4, 5, 6, 4, 5, 6, 4, 5, 6]
So basically it's looping over 'states' three times. Once for each element in 'state'. The syntax seems strange at first but in reality it's just acting like a nested for loop.
This could be written as:
new_list = []
for st in state:
for st in states:
new_list.append(st)
First we say for every element in in state, then for every element in states, append st to our list new_list. Because st is referenced in both loops, the value is dependent on the second list, states and is appended according to the number of elements in state.
edit: formatting and better explanation and fixing result (thanks jhdevos, it's too early to think without coffee!)
- jhdevos 15y agoYou've made a mistake with cut'n'paste, methinks. Actually, it is: >>> state = [1, 2, 3] >>> states = [4, 5, 6] >>> [st for s in state for st in states] [4, 5, 6, 4, 5, 6, 4, 5, 6]
- Herald_MJ 15y agoSo the code can be simplified as >>> states * len(state)
- llambda 15y agoJust the example. But this example is just to illustrate what's going on. It's not the same as what the author is trying to achieve.
- masklinn 15y agoThis code yes, in TFA's code the inner iteration (on `states`) depends on the result of the outer iteration (on `state`). For what it's worth, it's pretty easy to "unwrap" a Python listcomp: it's a sequence of nested loops, nested tests and a mapping. result = [mapping for iteration1 for iteration2 for iteration3 if test1 if test1] is equivalent (modulo some scoping interaction with the code outside it) to result = [] for iteration1 for iteration2 for iteration3 if test1 if test2 result.push(mapping) Apart from the final mapping, listcomps are executed strictly left to right, an evaluation can use anything produced to the "left" of it.