Back to BlogOct 2025

Python Comprehension

Introduction

List and Dictionaries comprehensions are important in Python because they make your code cleaner, faster, and more readable. In this post, we’ll also check out how to achieve similar results in JavaScript, using real-world examples to make things practical and fun.

Covering Python: List Comprenhesion

Without list comprehension, creating a new list often requires a for loop:

numbers = [1, 2, 3, 4, 5]
squared = []
for n in numbers:
    squared.append(n ** 2)
print(squared)  # [1, 4, 9, 16, 25]

With list comprehension, the same operation becomes:

squared = [n ** 2 for n in numbers]
print(squared)  # [1, 4, 9, 16, 25]

What is a list comprehension?

A list comprehension is a concise way to create a list by iterating over an iterable (like a list, range, or API response) and optionally filtering or transforming elements.

[expression for item in iterable if condition]

expression → what you want to include in the new list (can transform the item)

item → the variable representing each element

iterable → the data you’re looping over

if condition → optional filter

Let's dive deeper

Suppose we have an API that returns a list of users:

[
  {"id": 1, "name": "Alice", "age": 28, "email": "alice@example.com"},
  {"id": 2, "name": "Bob", "age": 22, "email": "bob@example.com"},
  {"id": 3, "name": "Charlie", "age": 35, "email": "charlie@example.com"}
]

// Example 1: Extract all user names
user_names = [user['name'] for user in users]
print(user_names)
// Output: ['Alice', 'Bob', 'Charlie']

// Example 2: Get emails of users over 30 years old
emails_over_30 = [user['email'] for user in users if user['age'] > 30]
print(emails_over_30)
// Output: ['charlie@example.com']

// Example 3: Create a list of user greeting messages
greetings = [f"Hello, {user['name']}!" for user in users]
print(greetings)
// Output: ['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']

Covering Python: Dictionaries Comprenhesion

Dictionary comprehensions let you create dictionaries in a single line, just like list comprehensions but with key-value pairs.

// Syntax
{key: value for item in iterable if condition}

Lets investigate some examples:

import requests

url = "https://api.spacexdata.com/v4/rockets"
rockets = requests.get(url).json()
// Example 1
rocket_costs = {r["name"]: r["cost_per_launch"] for r in rockets}

print(rocket_costs)
// {'Falcon 1': 6700000, 'Falcon 9': 50000000, 'Falcon Heavy': 90000000, 'Starship': 7000000}
// Example 2
users = requests.get("https://jsonplaceholder.typicode.com/users").json()

user_emails = {u["name"]: u["email"] for u in users}
print(user_emails)
// {'Leanne Graham': 'Sincere@april.biz', 'Ervin Howell': 'Shanna@melissa.tv', ...}
// Example 3 (Grouping Example)
rocket_countries = {}

rocket_countries = {
    country: sum(1 for r in rockets if r["country"] == country)
    for country in {r["country"] for r in rockets}
}

Lets see how we achieve similar results in Javascript

Given the following response from an API

countries = [
  {
    "country": "Australia",
    "language": "English",
    "states": [
      {"name": "New South Wales", "abbreviation": "NSW"},
      {"name": "Queensland", "abbreviation": "QLD"},
      {"name": "South Australia", "abbreviation": "SA"}
    ],
    "flagColors": ["green", "gold"]
  },
  {
    "country": "Canada",
    "language": "English/French",
    "states": [
      {"name": "Alberta", "abbreviation": "AB"},
      {"name": "British Columbia", "abbreviation": "BC"}
    ],
    "flagColors": ["red", "white"]
  },
  {
    "country": "New Zealand",
    "language": "English/Māori",
    "states": [
      {"name": "Auckland", "abbreviation": "AKL"},
      {"name": "Bay of Plenty", "abbreviation": "BOP"},
      {"name": "Canterbury", "abbreviation": "CAN"}
    ],
    "flagColors": ["blue", "red"]
  }
]

Get All Country Names:

// Python
country_names = [c["country"] for c in countries]
print(country_names)

// javascript
const countryNames = countries.map(c => c.country);
console.log(countryNames);

// Output: ['Australia', 'Canada', 'New Zealand']

Filter Countries That Have “Green” in Their Flag

// Python
green_flags = [c["country"] for c in countries if "green" in c["flagColors"]]
print(green_flags)

// javascript
const greenFlags = countries
  .filter(c => c.flagColors.includes("green"))
  .map(c => c.country);
console.log(greenFlags);

// Output: ['Australia']

Flatten All States into One List (Nested Data)

// Python
all_states = [s["name"] for c in countries for s in c["states"]]
print(all_states)

// Javascript
const allStates = countries.flatMap(c => c.states.map(s => s.name));
console.log(allStates);

// Output:
// ['New South Wales', 'Queensland', 'South Australia', 'Alberta', 
// 'British Columbia', 'Auckland', 'Bay of Plenty', 'Canterbury']

Conclusion

Python comprehensions are super handy for transforming, filtering, and organizing data in a clean, readable way — especially when you’re working with APIs. We also took a peek at how to do the same kind of stuff in JavaScript, which is a nice way to refresh your skills or pick up some new tricks for writing cleaner, more efficient code.

List comprehesion:

  • Extracting specific fields from JSON
  • Filtering data (if conditions)
  • Mapping or transforming values

Dictionary Comprehensions:

  • Creating lookup tables
  • Grouping or aggregating API data
  • Combining and filtering structured data

Python Playgrounds and practice:

// starting point
import requests
url = "https://api.spacexdata.com/v4/rockets"
rockets = requests.get(url).json()
print(rockets)

Exercises using List Comprehension

  1. Get the names of all rockets
  2. Get the first stage engines for each rocket
  3. Filter rockets that are still active
  4. Create a list of rocket names and their costs per launch
  5. Get the list of countries where rockets were built

These exercises are perfect for practicing:

  • Filtering (if in comprehension)
  • Mapping / transforming data (f"{...}")
  • Extracting nested JSON data (r['first_stage']['engines'])
Show Exercise Results
// 1
rocket_names = [r['name'] for r in rockets]
print(rocket_names)

//2
first_stage_engines = [r['first_stage']['engines'] for r in rockets]
print(first_stage_engines)

//3
active_rockets = [r['name'] for r in rockets if r['active']]
print(active_rockets)

//4
costs = [f"{r['name']} costs ${r['cost_per_launch']}" for r in rockets]
print(costs)

//5 
countries = [r['country'] for r in rockets]
print(countries)