Lesson 7: Collections — Lists and Loops

Create and manipulate lists; use for and while loops; iterate over data collections.

By • Last updated • 70 min

AI is all about data, and data rarely comes as a single number. It comes in collections.

In Python, the most common way to store a collection of items is a List.

Lists: Ordered Collections

A list is created using square brackets []. You can store numbers, strings, or even other lists inside.

predictions = [0.9, 0.1, 0.8, 0.4]
labels = ["cat", "dog", "bird"]

You can access items in a list using their index. Remember, Python is "zero-indexed", meaning the first item is at index 0.

print(labels[0]) # Output: cat

Loops: Automating Repetition

To do something with every item in a list, we use a for loop. This is crucial for iterating through datasets or simulating training steps!

for score in predictions:
    print(score)

If you want to loop a specific number of times, you can use the range() function:

for i in range(5):
    print(f"Training Epoch {i}")

Slicing and Changing Lists

Beyond picking out a single index, you can take a slice with list[start:stop]. The start is included and the stop is excluded, which is the same convention as range(). Negative indexes count from the end, so -1 is the last item. Lists are mutable and come with methods to grow and shrink them.

scores = [0.9, 0.3, 0.7, 0.85, 0.2]

print(scores[1:3])    # [0.3, 0.7]
print(scores[:2])     # [0.9, 0.3]   first two
print(scores[-1])     # 0.2          last item

scores.append(0.95)   # add to the end
scores[1] = 0.35      # replace an item
scores.remove(0.2)    # remove the first matching value
print(len(scores), sum(scores), max(scores))

Looping with enumerate and zip

Often you need the position as well as the value. Instead of managing a counter by hand, use enumerate(). When you have two parallel lists, such as predictions and true labels, zip() pairs them up.

labels = ["cat", "dog", "bird"]
for i, name in enumerate(labels):
    print(i, name)           # 0 cat / 1 dog / 2 bird

preds = [1, 0, 1, 1]
truth = [1, 0, 0, 1]
for p, t in zip(preds, truth):
    print("match" if p == t else "miss")

List Comprehensions

A list comprehension builds a new list from an old one in a single expression. It reads like the mathematical set-builder notation and is idiomatic Python in data work.

scores = [0.9, 0.3, 0.7, 0.85, 0.2, 0.95]

doubled = [s * 2 for s in scores]
high = [s for s in scores if s > 0.8]      # filter
print(high)                  # [0.9, 0.85, 0.95]
print(len(high))             # 3  (same answer as a counting loop)

Everything a comprehension does can be written as a normal loop with append; use whichever is clearer. If a comprehension needs more than one condition or becomes hard to read, switch to the loop.

while Loops and Stopping Conditions

A for loop runs once per item. A while loop runs as long as a condition stays true, which suits situations where you do not know the number of steps in advance, such as training until the error is small enough. The body must change something that eventually makes the condition false.

error = 1.0
epochs = 0
while error > 0.05:
    error = error * 0.7      # pretend each epoch cuts error by 30%
    epochs += 1
print(epochs, round(error, 4))   # 9 0.0404

break exits a loop early and continue skips to the next iteration. Always make sure a while loop has a way to finish; otherwise it runs forever and you will need to stop the program.

Common Pitfalls

  • Off-by-one errors. A list of 5 items has valid indexes 0 to 4. scores[5] raises IndexError, and range(5) stops at 4.
  • Changing a list while looping over it. Removing items inside the loop makes Python skip elements. Build a new list instead.
  • Aliasing. b = a does not copy the list; both names refer to the same one. Use a.copy() or a[:].
  • Forgetting the colon or indentation after for and while.
  • Averaging an empty list. sum(x) / len(x) divides by zero when x is empty.

Recap

  • Lists are ordered, zero-indexed and mutable; slices exclude the stop index.
  • for iterates over items, enumerate adds positions, zip pairs sequences.
  • Comprehensions build or filter lists concisely.
  • while repeats until a condition fails, so the body must make progress toward ending.

Coding Challenge: Evaluating Predictions

Let's simulate evaluating a model. You have a list of prediction scores between 0 and 1. We want to count how many predictions are above our threshold.

  1. Create a list scores = [0.9, 0.3, 0.7, 0.85, 0.2, 0.95].
  2. Create a variable high_confidence_count and set it to 0.
  3. Write a for loop to go through each score in scores.
  4. Inside the loop, use an if statement to check if the score is greater than 0.8. If it is, add 1 to your count.
  5. After the loop, print() the final count.
main.py
Run your code to see output here.