Learn Python in 30 Days — Day 22: Lists & Dictionary Comprehensions

Day 22: Lists & Dictionary Comprehensions

Welcome to Day 22 of the Learn Python in 30 Days series!

Today we get into one of Python’s cleanest “superpowers”: comprehensions.

These let you build lists, dictionaries, and sets in a single, readable line, perfect for filtering data, transforming it, or generating new structures without writing full loops.

By the end of today, you’ll know how to:

  • Turn long loops into compact one-liners

  • Build new lists from existing data

  • Filter items based on conditions

  • Create dictionaries on the fly

  • Use comprehensions with nested structures

This is the kind of Python feature that instantly makes your code cleaner and easier to read.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

What Is a Comprehension?

A comprehension is a compact way to create a new list or dictionary by looping over something.

squares = [] for n in range(1, 6): squares.append(n * n)
We can do the same by: -
squares = [n * n for n in range(1, 6)]

Same result but far more compact.

List Comprehensions

List comprehensions generate new lists based on an existing sequence.
They follow this pattern: -

[new_item for item in collection]

This means:
  • Take each item from a sequence

  • Transform it (or keep it as is)

  • Collect the results into a new list

It’s especially useful when you need to convert or reshape data.

Example: Convert temperatures from °C → °F

temps_c = [0, 10, 20, 30] temps_f = [(t * 9/5) + 32 for t in temps_c]
print(temps_c)
print(temps_f)

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Adding Filtering Conditions

You can attach an if statement at the end to keep only the items that match your rule.

This turns a comprehension into a combined filter + transform tool.
It prevents extra loops or awkward logic, and keeps your intent clear:

  • Iterate

  • Check a condition

  • Keep the values that pass

When working with text, sensor readings, user input, or API data, this is incredibly handy.

Example: Keep only even numbers

evens = [n for n in range(20) if n % 2 == 0]
print(evens)

Example: Extract short words

words = ["retro", "python", "kit", "maker", "loop"] short_words = [w for w in words if len(w) <= 4]
print(words) print(short_words)

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Dictionary Comprehensions

Dictionary comprehensions work just like list comprehensions, but they build key/value mappings.

Pattern:

{key: value for item in collection}

This is perfect when you want to restructure data, turn lists into dictionaries, or transform existing dictionaries.
Instead of manually creating a dict and assigning inside a loop, you express the whole transformation in one place.

Example: Map a list of names to their lengths

names = ["Matty", "Alice", "Bob"] name_lengths = {name: len(name) for name in names}
print(names)
print(name_lengths)

Example: Count character frequency

text = "banana" freq = {char: text.count(char) for char in set(text)}
print(freq)

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Transforming Dictionaries

Sometimes you already have a dictionary but want to modify the values, for example:

  • adjust prices

  • convert units

  • clean up strings

  • normalise data

Dictionary comprehensions let you “remap” a dictionary in one step by looping over .items().

It’s cleaner and reduces errors from accidentally mutating data in place.

Example: Convert all prices with tax added

prices = {"pedal": 40, "kit": 12, "resistors": 5} with_tax = {item: price * 1.2 for item, price in prices.items()}

print(prices)
print(with_tax)

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Comprehensions with Conditions in the Output

Instead of filtering items out, you can replace them using a conditional expression:

new_value_if_true if condition else other_value

This adds logic to the value-creation part of the comprehension.
It’s great for labelling data, cleaning text, or generating UI elements.

For example:

  • Tag numbers as "even"/"odd"

  • Flag values that exceed a threshold

  • Convert only some items to uppercase

You keep every element but transform them differently.

Example: Categorise numbers

labels = ["even" if n % 2 == 0 else "odd" for n in range(10)] print(labels)
Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Nested Comprehension

Nested comprehensions let you flatten nested lists or generate combinations.

It’s basically a compact version of writing two for-loops:

Great when dealing with nested lists or data structures from Day 13.

Flattening is a common pattern when working with:

  • matrices

  • grid-based games

  • pixel arrays

  • CSV data

  • embedded dictionaries/lists

The nested comprehension makes this clean and readable.

Example: Flatten a 2D list

grid = [[1, 2], [3, 4], [5, 6]] flat = [num for row in grid for num in row]
print(grid)
print(flat)

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub herehere and run it yourself.

Mini-Project: Keyword Highlighter

This small project shows how comprehensions can combine:

  • conditions

  • string methods

  • transforming values

  • looping

We take a list of words and highlight only the ones containing a chosen letter.

It mimics real-world tasks like:

  • searching logs

  • highlighting keywords in text

  • filtering filenames

  • analysing Python code tokens

Take a list of words and highlight only the ones that match a condition.

words = ["logic", "LED", "python", "pedal", "loop", "resistor"] target = "l" highlighted = [w.upper() if target in w.lower() else w for w in words] print(highlighted)

Output example:

['LOGIC', 'LED', 'python', 'PEDAL', 'LOOP', 'resistor']

This shows how filtering + transforming can combine into one clean comprehension.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Next Up — Day 23 – Working with JSON

Tomorrow, you’ll look into JSON and reading / writing structured data in this format.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

Math Behind Logic Gates

6502 - Part 2 Reset and Clock Circuit

Building a 6502 NOP Test