Loops


15 min.   |   Intermediate  

for Loops

Use for loops to iterate over items in a sequence like a list or range.

Comprehensions: Lists and Dictionaries

Directly create a list or dictionary using a for loop.

while Loops

Use while loops when you want to repeat something until a condition becomes False.

break

break exits the loop immediately.

continue

continue skips the rest of the current loop iteration and moves on to the next.

Looping with enumerate()

Use enumerate() to get both index and item while looping.

Looping with zip()

Use zip() to loop over two or more sequences at once.

Infinite Loop Danger

If the while condition is never False, the loop will run forever.

# WARNING: This loop runs forever unless manually stopped
# while True:
#     print("Infinite loop!")

Loops: Exercises

Tip Loops: Exercise 1

Compute the expected value \mathbb{E}[X] of a discrete random variable X with outcomes x_i and probabilities p_i:

\mathbb{E}[X] = \sum_i x_i \ p_i

Tip Loops: Exercise 2

Compute the variance of the dataset using the definition:

\mathrm{Var}(X) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2

Tip Loops: Exercise 3

Build all possible 2-character combinations from a list of strings.

Tip Loops: Exercise 4

Given data values x_1, x_2, \ldots, x_n and bins defined as intervals, compute the number of observations falling into each bin using a loop.

Bins used in this exercise:

  • [0, 10) for index 0
  • [10, 20) for index 1
  • [20, 30) for index 2
Tip Loops: Exercise 5

Given values x_1, x_2, \ldots, x_n, their min–max scaled version is

x_i^{\text{scaled}} = \frac{x_i - x_{\min}}{x_{\max} - x_{\min}}

Use a loop to compute the scaled values for the dataset.