Arrays · 4 / 23 Theory

Searching, filtering and calculating with lists

Once the data is stored, the usual thing is to ask questions about it.

Functions to calculate

marks = [7, 5, 9, 4]
print(sum(marks))              # 25
print(max(marks))              # 9
print(min(marks))              # 4
print(len(marks))              # 4
print(sum(marks) / len(marks)) # 6.25  (the average)

Searching for a value

y = 9
if y in marks:
    print(f"Number {y} exists")
else:
    print(f"Number {y} doesn't exist")

Filtering with a loop

You go through the list and add to another one only what meets the condition:

evens = []
for n in [5, 2, 4, 3, 1, 8]:
    if n % 2 == 0:
        evens.append(n)
print(evens)   # [2, 4, 8]

Filtering with a list comprehension

It is the short form, very common in Python: [expression for x in list if condition].

evens = [n for n in [5, 2, 4, 3, 1, 8] if n % 2 == 0]   # [2, 4, 8]
doubles = [n * 2 for n in [1, 2, 3]]                       # [2, 4, 6]

Positive and negative: splitting and averaging

data = [3.0, -5.0, 2.0, -1.0, 8.0]
positives = [n for n in data if n > 0]
negatives = [n for n in data if n < 0]

print(sum(positives) / len(positives))   # 4.333...
print(sum(negatives) / len(negatives))   # -3.0

It is the scheme of Search positive and negative numbers. Beware of the empty list: if there are no negatives, len(negatives) is 0 and the division raises ZeroDivisionError. Check first with if negatives:.

Position of the maximum

values = [4, 9, 2, 9]
largest = max(values)
print(values.index(largest))   # 1  (the first position of the maximum)