[Tutor] Debugging While Loops for Control
Peter Otten
__peter__ at web.de
Fri Feb 17 19:23:53 CET 2012
Alan Gauld wrote:
>>The "x for x in y:" syntax makes it harder to follow for learners,
>
> Read about list comprehensions first.
> It helps if you studied sets in math at school. The format is
> somewhat like the math notation for defining a set. But FWIW it took me
> a long time to get used to that syntax too.
To grok list comprehensions it helps to write the equivalent for loops
first. You can mechanically convert
items = []
for x in "abcd":
if x < "d":
if x != "b":
items.append(x)
to
items = [x for x in "abcd" if x < "d" if x != "b"]
The for loops and ifs stay in place, the expression passed to append() in
the innermost loop moves to the beginning. Another example:
items = []
for x in "abcd":
if x < "d":
for y in x + x.upper():
if y != "A":
items.append(y*2)
This becomes
items = [y*2 for x in "abcd" if x < "d" for y in x + x.upper() if y != "A"]
Real-world list comprehensions tend to be less complicated, but to
understand them you just have to reverse the conversion:
items = [y*2
for x in "abcd"
if x < "d"
for y in x + x.upper()
if y != "A"
# append y*2
]
More information about the Tutor
mailing list