Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Tuesday, May 22, 2012

Nested for comprehensions

I think nested for loops seem a bit counterintuitive at first sight but the basic rule is that you start with outer loop(s) and end with inner loop(s). The only thing to remember is that you collect the result from the last inner loop at the very beginning.
text = 'Check carefully how nested for loops work!'
print ' '.join([letter.upper() for word in text.split() for letter in word]) 

C H E C K C A R E F U L L Y H O W N E S T E D F O R L O O P S W O R K !

You can also use guards (if statements) in for comprehensions. Below an example filtering out words that contain the letter 'o'.
text = 'Check carefully how nested for loops work!'
print ' '.join([letter.upper() for word in text.split() if word.find('o') != -1 for letter in word]) 

H O W F O R L O O P S W O R K !

No comments:

Post a Comment