Lesson 1 of 7 · 14 min · 1 hands-on step

Lists, Dictionaries & Loops

Python's workhorse data structures, plus list comprehensions.

Lists

Python · try it
skills = ["HTML", "CSS", "Python"]
skills.append("SQL")
skills[0]        # "HTML"
skills[-1]       # "SQL" (negative index counts from the end)
len(skills)      # 4

Dictionaries

Key-value pairs, like JavaScript objects:

Python · try it
user = {"name": "Ada", "age": 36}
user["name"]            # "Ada"
user.get("email", "-")  # "-" when the key is missing (no crash)
user["age"] = 37

Loops

for skill in skills:
    print(skill)

for i, skill in enumerate(skills):
    print(i, skill)

for key, value in user.items():
    print(key, value)

List comprehensions

A compact way to build lists, the Pythonic version of map and filter:

Python · try it
prices = [10, 25, 5]
with_tax = [p * 1.2 for p in prices]
expensive = [p for p in prices if p > 8]

Use them when they're easy to read. If a comprehension needs a comment to explain it, a regular loop is better.

🧪 Practice

Write word_count(text) that returns a dictionary mapping each lowercased word to how many times it appears.

word_count("the cat and The hat")
# {"the": 2, "cat": 1, "and": 1, "hat": 1}

Words are separated by spaces. An empty string returns {}.

Python
def word_count(text):
    counts = {}
    # your code here
    return counts

print(word_count("the cat and The hat"))

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What does [n * 2 for n in [1, 2, 3]] produce?

  2. Which structure gives fast lookup by key?

Create a free account to track your progress.