Exercise 1: List Comprehension Mastery

📅

|

👁️

2 views

|

❤️

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:

  1. for word in words → iterate through each word
  2. if len(word) >= 4 → keep only words with 4+ characters
  3. word.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]

Share this page to Telegram

التنقل بين المقالات

المقال السابق:

اترك رد

اكتشاف المزيد من موقع لطائف التنبيهات

اشترك الآن للاستمرار في القراءة والحصول على حق الوصول إلى الأرشيف الكامل.

متابعة القراءة

اكتشاف المزيد من موقع لطائف التنبيهات

اشترك الآن للاستمرار في القراءة والحصول على حق الوصول إلى الأرشيف الكامل.

متابعة القراءة