I'm reading the Python wikibook and feel confused about this part:
List comprehension supports more than one for statement. It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest.
>>>item = [x+y for x in 'cat' for y in 'pot'] >>>print item ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
I understand the usage of nested for loops but I don't get
...and will loop over the shorter objects if one object is longer than the rest
What does this mean? (shorter, longer...)
Well, the Python documentation does not talk of any such short/long case: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions. Having two "for" in a list comprehension means having two loops. The example pointed by @drewk is correct.
Let me copy it for the sake of explanation:
In both cases, the first "for" forms the outer loop and hte second "for" forms the inner loop. That is the only invariant here.
These type of nested loops create a Cartesian Product of the two sequences. Try it:
The inner 'x' in the list comprehension above (ie, the
for x in 'cat'
part) the is the same as the outerfor x in 'cat':
in this example:So the effect of making one shorter or longer is the same as making the 'x' or 'y' loop longer in two nested loops:
In each case, the shorter sequence is looped over again until the longer sequence is exhausted. This unlike
zip
where the pairing would be terminated at the end of the shorter sequence.Edit
There seems to be confusion (in the comments) about nested loops versus zip.
Nested Loops:
As shown above, this:
is the same as two nested 'for' loops with 'x' the outer loop.
Nested loops will execute the inner
y
loop the range ofx
in the outer loop times.So:
You can get the same result with product from itertools:
Zip is similar but stops after the shorter sequence is exhausted:
You can use itertools for a zip that will zip until the longest sequence is exhausted, but the result is different: