Traversing and selecting

Lesson 34 of 54 · Python Foundations

A for loop visits items in order. Use the item directly when its position is unnecessary. Accumulate results in a new list rather than removing items from the list being traversed.

readings = [12, 7, 14, 7]
low = []
count = 0
for reading in readings:
    if reading < 10:
        low.append(reading)
        count += 1
print(low)
print(count)
print(7 in readings, 9 not in readings)
[7, 7]
2
True True

Membership with in asks whether an equal item exists; it does not count occurrences. Use readings.count(7) when the count of a particular value is needed. Comparisons of strings are case-sensitive.

Sometimes position connects two lists. The following assumes equal lengths and that entries at each position describe the same station:

before = [8, 5, 9]
after = [10, 4, 11]
for index in range(len(before)):
    if after[index] > before[index]:
        print(index, before[index], after[index])
0 8 10
2 9 11

If the second list is shorter, indexing it can raise IndexError; if it is longer, this loop ignores its extra entries. Validate the relationship when the data does not guarantee it.