I’m having a hard time understanding why the positioning of an identical conditional statement within a list comprehension of multiple iterables would affect the result.
>>> boys = 'Jim','Jeff'
>>> girls = 'Bonnie', 'Buffy'
# This generates four tuples as expected
>>> [(b,g) for b in boys for g in girls]
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie'), ('Jeff', 'Buffy')]
# If the conditional "if b[-1] not in g" is at the end of the LC we get 3
>>> [(b,g) for b in boys for g in girls if b[-1] not in g]
[('Jim', 'Bonnie'), ('Jim', 'Buffy'), ('Jeff', 'Bonnie')]
# If the conditional is after the first sequence, we only get two results
>>> [(b,g) for b in boys if b[-1] not in g for g in girls]
[('Jim', 'Bonnie'), ('Jim', 'Buffy')]
Apologies in advance if someone else has already asked/answered this question on StackOverflow.
What you did is the same as:
Since
bandgare already defined and filled with values from the last run, the following happens:Jim.minBuffy? No – run inner loop:(Jim, Bonnie)(Jim, Buffy)JefffinBuffy? Yes – skip inner loop.If you had run this first in a new Python shell, it would have raised an
Exception: