Python Intermediate Lesson 2: Comprehensions, Generators and Sorting

Python Intermediate Lesson 2: Comprehensions, Generators and Sorting 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 2 of 10

Advertisement
In this article
  1. Generators: one item at a time
  2. Common mistakes
  3. Practice

Most loops that build a list or count something can be one readable line.

Loop version Comprehension
out = []
for r in rows:
  if r["status"] == "Pending":
    out.append(r["invoice"])
[r["invoice"] for r in rows if r["status"] == "Pending"]
reps = {r["rep"] for r in rows}                                  # set: unique values
by_rep = {rep: sum(1 for r in rows if r["rep"] == rep) for rep in sorted(reps)}   # dict
qty = sum(int(r["qty"]) for r in rows if r["qty"])              # generator: no list in memory
top = sorted(by_rep.items(), key=lambda kv: kv[1], reverse=True)[:2]
for i, (rep, n) in enumerate(top, start=1):
    print(f"{i}. {rep:<7} {n:>3}")

Generators: one item at a time

A comprehension in round brackets, or a function with yield, produces values on demand. Summing a 2 GB log file line by line uses almost no memory:

def big_amounts(path):
    for line in open(path):
        amt = float(line.split(",")[3])
        if amt > 100000:
            yield amt
print(sum(big_amounts("ledger.csv")))
πŸ’‘ Use key= for any custom sort: sorted(rows, key=lambda r: (r["region"], -float(r["amount"]))) sorts by region, then amount high to low.

Common mistakes

  • Nested comprehensions three levels deep: write a normal loop; readability wins.
  • Reusing a generator: it’s empty after one pass. Make a list if you need it twice.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 2 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 934 B
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 412 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *