+ 1

can anyone explain me what happened here? I just guessed "if len(x)>4" for list comprehension but didn't get it properly

words = ["tree", "button", "cat", "window", "defenestrate"] # Use a list comprehension to filter out words longer than four letters # Display the filtered list words2 = [x for x in words if len(x) > 4 ] print(words2)

2nd Aug 2024, 3:49 PM
Joy
Joy - avatar
2 Answers
+ 5
Maybe it will help to rewrite in an uncompressed form: words2 = [] for x in words: if len(x) > 4: words2.append(x) If the length is greater than 4, then the word is added to the list. We loop through each word of the list and identify the word with the variable 'x'. The list comprehension can be read the same way. x <-- adding x to the list for x in words <--- Iterate through each word, call it x if len(x) > 4 <-- Only add x to the list if the word has more than 4 characters. Putting it all together as a new list: words2 = [x for x in words if len(x) > 4]
2nd Aug 2024, 4:07 PM
Rrestoring faith
Rrestoring faith - avatar
+ 7
the list comprehension is equivalent to this loop words2 = [] for x in words: if len(x) > 4: words2.append(x)
2nd Aug 2024, 4:05 PM
Lisa
Lisa - avatar