Exercise 1: List Comprehension Mastery
Practice Problem: Write a single-line list comprehension that takes a list of strings, filters out strings shorter than 4 characters, and converts the remaining strings to uppercase.
Exercise Purpose: List comprehensions are a hallmark of Pythonic code. They allow you to replace verbose for loops and .append() calls with a readable, optimized single line. This exercise teaches you how to combine transformation (uppercase) and filtering (length check) in one expression.
Given Input: words = [“apple”, “bat”, “cherry”, “dog”, “elderberry”]
Expected Output: [‘APPLE’, ‘CHERRY’, ‘ELDERBERRY’]
The one-line list comprehension is:
words = ["apple", "bat", "cherry", "dog", "elderberry"]result = [word.upper() for word in words if len(word) >= 4]print(result)
Output:
['APPLE', 'CHERRY', 'ELDERBERRY']
How it works
[word.upper() for word in words if len(word) >= 4]
Think of it as:
for word in words→ iterate through each wordif len(word) >= 4→ keep only words with 4+ charactersword.upper()→ convert the selected words to uppercase
Equivalent traditional loop:
result = []for word in words: if len(word) >= 4: result.append(word.upper())
So the key pattern to remember is:
[transformation for item in iterable if condition]



اترك رد