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 compreh…


This content originally appeared on DEV Community and was authored by M.T.Ramkrushna

🛒 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)

With comprehension:

squares = [n*n for n in range(1, 6)]

Cleaner, faster, more readable.

🍫 2. List Comprehension (Core Formula)

General pattern

[new_item   for item in iterable   if condition]

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']

🎧 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]

🛍️ Example 3: Add “₹” symbol to all prices

You grab prices from a website:

prices = [200, 450, 1200]

formatted = [f"{p}" for p in prices]

🚗 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']

🧮 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]

Think of unzipping multiple packets into one tray.

🗃️ 5. Dictionary Comprehensions

Structure:

{key: value   for item in iterable   if condition}

🧾 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()}

📱 Example 2: Count lengths of all usernames

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

length_map = {u: len(u) for u in users}

⭐ 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()
}

🧩 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}

🏁 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}

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]]


This content originally appeared on DEV Community and was authored by M.T.Ramkrushna


Print Share Comment Cite Upload Translate Updates
APA

M.T.Ramkrushna | Sciencx (2025-11-27T12:34:16+00:00) 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions). Retrieved from https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/

MLA
" » 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions)." M.T.Ramkrushna | Sciencx - Thursday November 27, 2025, https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/
HARVARD
M.T.Ramkrushna | Sciencx Thursday November 27, 2025 » 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions)., viewed ,<https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/>
VANCOUVER
M.T.Ramkrushna | Sciencx - » 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/
CHICAGO
" » 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions)." M.T.Ramkrushna | Sciencx - Accessed . https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/
IEEE
" » 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions)." M.T.Ramkrushna | Sciencx [Online]. Available: https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/. [Accessed: ]
rf:citation
» 5. PYTHON ESSENTIALS FOR AI/ML (List & Dictionary Comprehensions) | M.T.Ramkrushna | Sciencx | https://www.scien.cx/2025/11/27/5-python-essentials-for-ai-ml-list-dictionary-comprehensions/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.