List and dictionary comprehensions are concise ways to create lists and dictionaries in Python.
Both are used for creating new sequences or mappings from existing iterables, but they differ in structure and output type.
| Feature | List Comprehension | Dict Comprehension |
|---|---|---|
| Purpose | Creates a new list | Creates a new dictionary |
| Syntax | [expression for item in iterable if condition] | {key: value for item in iterable if condition} |
| Output Type | List | Dictionary |
| Use Case | When you need a list of computed values | When you need key-value pairs generated dynamically |
🧩 Example:
# List Comprehension Example
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print("List Comprehension:", squares)
# Dict Comprehension Example
squares_dict = {n: n**2 for n in numbers}
print("Dict Comprehension:", squares_dict)Output:
List Comprehension: [1, 4, 9, 16, 25]
Dict Comprehension: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}