by llambda · 15y ago · 0 comments
>>> 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!)
>>> 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]>>> states * len(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.