DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions)

๐Ÿ›’ 1. What Are Comprehensions?

Comprehensions are a compact and expressive way to create lists and dictionaries.

Instead of writing long loops, you write everything in one clean line.

Classic loop vs comprehension

Without comprehension:

squares = []
for n in range(1, 6):
    squares.append(n*n)
Enter fullscreen mode Exit fullscreen mode

With comprehension:

squares = [n*n for n in range(1, 6)]
Enter fullscreen mode Exit fullscreen mode

Cleaner, faster, more readable.


๐Ÿซ 2. List Comprehension (Core Formula)

General pattern

[new_item   for item in iterable   if condition]
Enter fullscreen mode Exit fullscreen mode

Visual

Imagine you have a conveyor belt of items.
Comprehension โ†’ picks items โ†’ maybe filters โ†’ transforms โ†’ outputs a new list.


๐Ÿฅค 3. Real-Life Examples (Very Relatable)

๐ŸŸ Example 1: Filter items from a food list

Suppose you ordered a mixed snack bundle and want to keep only healthy items.

foods = ["chips", "salad", "pizza", "fruits"]

healthy = [f for f in foods if f in ["salad", "fruits"]]
print(healthy)   # ['salad', 'fruits']
Enter fullscreen mode Exit fullscreen mode

๐ŸŽง Example 2: Increase volume of all songs

Imagine a music app increases the volume of every song by 10%.

volumes = [40, 60, 80]
new_volumes = [v + 10 for v in volumes]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ›๏ธ Example 3: Add โ€œโ‚นโ€ symbol to all prices

You grab prices from a website:

prices = [200, 450, 1200]

formatted = [f"โ‚น{p}" for p in prices]
Enter fullscreen mode Exit fullscreen mode

๐Ÿš— Example 4: Extract only electric cars

cars = [
    {"model": "Tesla", "type": "EV"},
    {"model": "BMW", "type": "Petrol"},
    {"model": "Tata Nexon", "type": "EV"}
]

ev_models = [car["model"] for car in cars if car["type"] == "EV"]
print(ev_models)  # ['Tesla', 'Tata Nexon']
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฎ 4. Nested List Comprehension

๐ŸŽ’ Example: Flatten a list of student groups

groups = [[1, 2], [3, 4], [5, 6]]

flat = [student for group in groups for student in group]
print(flat)  # [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Think of unzipping multiple packets into one tray.


๐Ÿ—ƒ๏ธ 5. Dictionary Comprehensions

Structure:

{key: value   for item in iterable   if condition}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ 6. Real-Life Dictionary Examples

๐Ÿ“ฆ Example 1: Price after discount

You have a price list and want to apply 10% discount.

prices = {"shoes": 2000, "shirt": 1200, "watch": 5000}

discounted = {item: price*0.9 for item, price in prices.items()}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฑ Example 2: Count lengths of all usernames

users = ["ali", "coder_123", "sara"]

length_map = {u: len(u) for u in users}
Enter fullscreen mode Exit fullscreen mode

โญ Example 3: Create mapping of product โ†’ โ€œIn Stockโ€/โ€œLow Stockโ€

stock = {"laptop": 5, "mouse": 0, "keyboard": 2}

status = {
    item: ("In Stock" if qty > 0 else "Out of Stock")
    for item, qty in stock.items()
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฉ 7. Combined Example

(Super realistic & used in ML/Data)

๐Ÿงช Convert a list of temperatures into a dict

temps = [28, 31, 36]

weather = {t: "Hot" if t > 30 else "Cool" for t in temps}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ 8. When to Use Comprehensions

โœ” transforming data
โœ” filtering data
โœ” flattening lists
โœ” building dicts from large datasets
โœ” feature preprocessing in ML

Avoid when:
โœ˜ The logic becomes too long or unreadable
โœ˜ Multiple if/loops make it messy
(then use normal loops)


๐Ÿงช 9. Mini Exercises (Try These!)

Send me your answers โ€” Iโ€™ll check and correct if needed.

Exercise 1

Create a new list of squares from 1 to 20 only for even numbers.


Exercise 2

Given a list of names, create a dict โ†’ name โ†’ uppercase version.


Exercise 3

You have this dict:

products = {"mouse": 500, "laptop": 60000, "usb": 200}
Enter fullscreen mode Exit fullscreen mode

Create a new dict where:

  • items > 1000 become โ€œExpensiveโ€
  • else โ€œCheapโ€

Exercise 4

Flatten this list using comprehension:

matrix = [[1,2,3], [4,5,6]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)