Menu

1D Arrays

Condition-based array processing

Some array tasks do more than print every element: they count elements that meet a condition, change elements that meet a condition, or report whether a particular value appears anywhere. Each one works through the array with a loop and tests every element inside it.

Counting and changing

To count, make a counter and set it to 0 before the loop. Inside the loop, add 1 to the counter only when the current element meets the condition. Keep the counter outside the loop so it keeps its value between passes; resetting it inside would throw away the earlier counts.

To change elements, assign a new value to the element's index inside the loop — for example, add 3 to every height below 10. Use an index loop when you need to write back into the array; looping directly over the items gives you each value but not its position.

plant_heights = [8, 12, 6, 15, 9]
for i in range(len(plant_heights)):
    if plant_heights[i] < 10:
        plant_heights[i] = plant_heights[i] + 3
print(plant_heights)

Output:

[11, 12, 9, 15, 12]

Checking whether a value appears

A Boolean flag is a variable that is either True or False. Set it to False before the loop. Inside the loop, set it to True when the matching value is found. After the loop, test the flag once and print the result, so the message is produced only once.

Printing a not-found message inside the loop with an else is a logic error. The else runs for every element that does not match, so a later match cannot cancel the earlier messages and you may report that the value is not found even when it is there. The decision can only be made after every element has been checked.

batteries = [88, 100, 14, 52, 7, 93]
low_count = 0
full_battery = False
for i in range(len(batteries)):
    if batteries[i] < 20:
        low_count = low_count + 1
    if batteries[i] == 100:
        full_battery = True
print("Low batteries:", low_count)
print("Battery at 100% found:", full_battery)

Output:

Low batteries: 2
Battery at 100% found: True

Practise this