Why this matters
Most Python tools start with raw data. Names, emails, marks, product lists, bug reports, prompts, or API results.
Before you call an API, you often need to clean and reshape that data. Comprehensions help you do that in one readable line.
One idea
A comprehension means: make a new collection from an old one, while changing or filtering each item.
Use it when the logic is simple. If it becomes hard to read, use a normal loop.
List comprehension
Say your sample input has student names from a college event form. Some have extra spaces. Some are blank.
You can clean them before saving or sending them anywhere.
raw_names = [" Asha ", "", "Ravi", " Meera", " "]
clean_names = [name.strip() for name in raw_names if name.strip()]
print(clean_names)
# ['Asha', 'Ravi', 'Meera']Shape rows
Your tool may read rows later from a CSV or JSON file. For now, think of rows as a list of dictionaries.
This example keeps only valid rows and shapes them into a smaller format for an API request.
students = [
{"name": "Asha", "email": "[email protected]", "score": 82},
{"name": "Ravi", "email": "", "score": 76},
{"name": "Meera", "email": "[email protected]", "score": 91},
]
api_payload = [
{"student_name": s["name"], "contact": s["email"]}
for s in students
if s["email"]
]
print(api_payload)
# [{'student_name': 'Asha', 'contact': '[email protected]'}, {'student_name': 'Meera', 'contact': '[email protected]'}]Read the pattern
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Ask AI carefully
AI tools are useful for writing comprehensions from a plain English rule. Give the input shape and the exact output shape.
Always check three things in the answer: missing keys, empty values, and whether the code changes the original data by mistake.
Prompt you can use:
I have this Python list of dictionaries. Write a readable list comprehension that keeps only rows with email and creates dictionaries with keys student_name and contact. Do not mutate the original list.
students = [
{"name": "Asha", "email": "[email protected]", "score": 82},
{"name": "Ravi", "email": "", "score": 76}
]Common mistake
Do not pack too much logic into one comprehension. Nested conditions, multiple conversions, and API calls inside it make debugging painful.
Keep API calls out of comprehensions. First shape the data. Then loop over the clean payload when you call the API or mock API.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done