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.
A list is created using square brackets []. You can store numbers, strings, or even other lists inside.
You can access items in a list using their index. Remember, Python is "zero-indexed", meaning the first item is at index 0.
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!
If you want to loop a specific number of times, you can use the range() function:
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))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")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.
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.0404break 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.
scores[5] raises IndexError, and range(5) stops at 4.b = a does not copy the list; both names refer to the same one. Use a.copy() or a[:].for and while.sum(x) / len(x) divides by zero when x is empty.for iterates over items, enumerate adds positions, zip pairs sequences.while repeats until a condition fails, so the body must make progress toward ending.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.
scores = [0.9, 0.3, 0.7, 0.85, 0.2, 0.95].high_confidence_count and set it to 0.for loop to go through each score in scores.if statement to check if the score is greater than 0.8. If it is, add 1 to your count.print() the final count.