Python Lesson 4: Lists and Dictionaries

Python Lesson 4: Lists and Dictionaries featured illustration

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 Python Beginner Course · Lesson 4 of 12

In this article
  1. Lists
  2. Dictionaries
  3. Nesting
  4. Tuples and sets, briefly
  5. Where beginners go wrong
  6. Practice
  7. Continue learning

One variable holds one value. Real data has many: all regions, every product’s price. Python’s two workhorses for this are lists (an ordered column of values) and dictionaries (a lookup table of key → value).

Advertisement

Lists

regions = ["North", "South", "East", "West"]
regions[0]          # 'North'  (counting starts at 0)
regions[-1]         # 'West'   (negative counts from the end)
regions[1:3]        # ['South', 'East']  (slice: from 1 up to, not including, 3)
len(regions)        # 4
regions.append("Central")
sorted(regions)     # a sorted copy; regions.sort() sorts in place
"East" in regions   # True

Dictionaries

prices = {"Laptop": 42000, "Monitor": 12800, "Printer": 9500}
prices["Monitor"]                 # 12800
prices["Router"] = 3400           # add or change
prices.get("Mouse", "not in list")  # safe lookup with a default
for name, price in prices.items():
    print(name, price)

A dictionary is VLOOKUP built in: prices[code] instead of =VLOOKUP(code, table, 2, FALSE). prices["Mouse"] raises a KeyError when missing; .get() doesn’t.

💡 Dictionary keys must be unique, just like a lookup column should be. Adding the same key again overwrites the old value instead of creating a duplicate.

Nesting

order = {"id": "SO-1001", "customer": "Iyer Stores",
         "items": [("Laptop", 2), ("Router", 3)]}
total = sum(prices[p] * q for p, q in order["items"])

Lists of dictionaries are how JSON data from websites and APIs looks.

Advertisement

Tuples and sets, briefly

  • Tuple ("Laptop", 2): like a list, but can’t be changed. Good for fixed pairs.
  • Set {"North", "South"}: unique values, no order. set(list_with_repeats) removes duplicates.

Where beginners go wrong

Error Cause
IndexError: list index out of range regions[4] on a 4-item list (last is [3])
KeyError: ‘Mouse’ Key missing; use .get()
sorted() “didn’t work” It returns a new list; assign it or use .sort()

Practice

Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.

📎 Practice files for this article

⬇ Download all 2 files (ZIP · 784 B)

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