Max, Min, and Sum

An iterable is anything you can step through, like a string, list, or tuple. While you could write a for loop to find the highest value in a list of scores, Python’s built-in functions are faster and much cleaner.

  • max(): Returns the largest item.
  • min(): Returns the smallest item.
  • sum(): Adds up all numerical items.
# Analyzing a list of stock prices
prices = [120.50, 98.20, 150.00, 110.75]

print(max(prices))  # 150.0
print(min(prices))  # 98.2
print(sum(prices))  # 479.45

You can also use min() and max() on strings. min() returns the item that comes first in a dictionary (A-Z), and max() returns the one that comes last.

names = ["Alice", "Zeke", "Bob", "Charlie"]

print(min(names))  # Output: Alice (First in the alphabet)
print(max(names))  # Output: Zeke (Last in the alphabet)

Python compares characters using their underlying numeric codes (ASCII/Unicode). In this system, all uppercase letters come before lowercase letters.

# Even though 'a' is at the start of the alphabet, 'Z' wins the min() race.
print(min(["apple", "Zebra"])) # Output: Zebra

Python doesn’t have a built-in average() function because it’s so easy to calculate using sum() and len().

class_results = {"Alice": 92, "Bob": 78, "Charlie": 99}

scores = class_results.values()

# Standard formula: Total / Count
average = sum(scores) / len(scores)

print(f"Class Average: {average}") # 89.66

Pairing Data with zip()

Imagine you have two separate lists: one with Products and one with Prices. The zip() function acts like a physical zipper, locking the elements together into pairs (tuples).

products = ["Laptop", "Mouse", "Monitor"]
stock = [15, 42, 7]

# Pairing them in a loop
for name, count in zip(products, stock):
    print(f"We have {count} {name}s.")

Turning Lists into a Dictionary

One of the most common uses for zip() is taking two lists and turning them into a single dictionary in one line. This is a huge time-saver when processing data.

products = ["Laptop", "Mouse", "Monitor"]
stock = [15, 42, 7]

# Super useful conversion:
inventory_dict = dict(zip(products, stock))

print(inventory_dict) # {'Laptop': 15, 'Mouse': 42, 'Monitor': 7}

The “Shortest List” Rule

If you try to zip two lists of different lengths, Python won’t complain or crash. Instead, it stops as soon as the shortest list is finished. Any extra data in the longer list is simply ignored.

names = ["Alice", "Bob", "Charlie"]
ids = [1, 2]

# Charlie will be ignored because ids only has 2 items.
paired = list(zip(names, ids))
print(paired) # [('Alice', 1), ('Bob', 2)]