Nested Loops

The body of a for loop can contain any code, including another for loop. Nested for loops can be useful when used prudently, but they also have the potential to drastically slow down your program. To see why, imagine that you want to loop through a list of your Facebook friends, and for each of your friends, you want to loop through all their Facebook posts looking for a certain word (“Have any of my friends ever posted about for loops?”). Suppose that the average Facebook user has 100 posts. If you have just one friend, you need to execute the inner for loop only about 100 times, but if you have two friends, you have to execute the inner for loop about 200 times. The number of times the inner for loop is executed increases much ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.