Skip to main content

Ex 23: List Comprehension Challenges

Problem

Mastering list comprehensions requires practice with various data types and nested structures. Complete the following four tasks:

  1. Squares: Generate a list of squares for numbers from 1 to 20.
  2. Length Filter: From a list of words, keep only those longer than 4 characters.
  3. Flattening: Flatten a nested list of integers (e.g., [[1, 2], [3, 4]]) into a single flat list.
  4. Palindromes: From a list of strings, return each string reversed—but only if the original string is a palindrome.

Rules

  • All tasks must be solved using a single-line list comprehension.
  • For Task 2, use the list: ["cat", "elephant", "dog", "python", "owl", "snake"].
  • For Task 4, use the list: ["racecar", "hello", "level", "world", "madam", "python"].

Boilerplate

Copy below code and paste to our IDE for head start.

# Task 1: Squares
squares = []

# Task 2: Length Filter
words = ["cat", "elephant", "dog", "python", "owl", "snake"]
filtered_words = []

# Task 3: Flattening
nested = [[1, 2], [3, 4], [5, 6]]
flat_list = []

# Task 4: Palindromes
strings = ["racecar", "hello", "level", "world", "madam", "python"]
palindromes = []

Expected output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
['elephant', 'python', 'snake']
[1, 2, 3, 4, 5, 6]
['racecar', 'level', 'madam']

Solution

Only view the solution after trying our best.

Show solution
# 1. Squares
squares = [num**2 for num in range(1, 21)]

# 2. Length Filter
words = ["cat", "elephant", "dog", "python", "owl", "snake"]
filtered_words = [word for word in words if len(word) > 4]

# 3. Flattening
nested = [[1, 2], [3, 4], [5, 6]]
flat_list = [num for sublist in nested for num in sublist]

# 4. Palindromes
strings = ["racecar", "hello", "level", "world", "madam", "python"]
palindromes = [word[::-1] for word in strings if word[::-1] == word]

Details

  • Task 3: When flattening, the first for loop iterates over the outer containers, and the second for loop iterates over the items inside those containers.
  • Task 4: We use the [::-1] slicing trick to reverse the string and compare it to itself to identify palindromes.