Nested loops are loops within loops. They allow you to iterate over multiple dimensions of data or perform complex operations that require multiple levels of iteration. In data analytics, nested loops can be useful for processing multi-dimensional datasets, such as matrices or tables with multiple variables.
Let’s imagine that we have a players dictionary, and each player contains a list games, and each game contains a list of shots/goals entered as 0 for shot and 1 for goal. Then we want to calculate the average shot accuracy for each player.
To calculate the average shot accuracy for each player, we need to loop over the dictionary of players, then loop over each player’s games, and finally loop over each shot/goal in those games. We can use nested loops to achieve this.
for player, games in players.items(): tot_shots =0 tot_goals =0 tot_games =len(games)for game in games: tot_shots +=len(game) tot_goals +=sum(game) accuracy = tot_goals / tot_shots *100print(f"{player} - Accuracy: {accuracy:.2f}% over {tot_games} games")
Messi - Accuracy: 66.67% over 2 games
Ronaldinho - Accuracy: 50.00% over 2 games
Neymar - Accuracy: 66.67% over 2 games
Mbappe - Accuracy: 66.67% over 2 games
Ronaldo - Accuracy: 50.00% over 2 games
When we working with nested loops, it’s important to keep track of the indentation levels to ensure that the loops are correctly nested. Secondly, be cautious with the naming of loop variables to avoid confusion. In the example above, we used player, games, and game as loop variables to clearly indicate their purpose. Notice that we are using both plural and singular forms to differentiate between the collection and the individual item.