+ 1

Why does this code works like this?

https://www.sololearn.com/en/compiler-playground/c7v2xI4BjGBI Why did i need to create a new list to perform comprehension on it, without later calling it, in order to get the desired output? The task: Given a list of words, use a list comprehension to create a new list that includes only the words that are longer than 4 letters. Why does printing the newly created list (word4) gives [None, None] as output?

10th Sep 2024, 12:22 PM
Igor Matić
Igor Matić - avatar
5 Antworten
+ 2
words = ["tree", "button", "cat", "window", "defenestrate"] # Use a list comprehension to filter out words longer than four letters [words.remove(w) for w in words if len(w) < 5] word4 = words # Display the filtered list print(words) print(word4) In the line, "[words.remove(w) for w in words if len(w) < 5]", it actually edits the list interatively. If you wanted to have a copy of that list in words4, do the assignment after and it works. Honestly you don't need to make a copy of the list. The variable words4 is unnecessary.
10th Sep 2024, 2:10 PM
Jerry Hobby
Jerry Hobby - avatar
+ 3
"Why does printing the newly created list (word4) gives [None, None] as output?" The remove() method you used inside the comprehension construction returns nothing (None). That is why you get `None` inside <word4>, for when a method returns nothing, a `None` will be there as you have seen. The two `None` in <word4> represents "tree" and "cat", two words whose length was less than 5. Add more short words in <words> and you will see, more `None` will appear in <word4>. P.S. You don't need to use remove() method, look here... word5 = [w for w in words if len(w) < 5] It generates matching data without altering <words>.
10th Sep 2024, 3:29 PM
Ipang
+ 2
the use of: [words_1.remove(w) for w in words_1 if len(w) < 5] is not a real comprehension, but it uses the internal for loop of it. comprehensions are designed to create a new list output from an input iterable. so the task can also be done in a simple `for loop` (3 lines code + output): words_1 = ["tree", "button", "cat", "window", "defenestrate"] for word in words_1: if len(word) < 5: words_1.remove(word) print(words_1) # => result will be: ['button', 'window', 'defenestrate'] > an issue that has *NOT* been adressed yet in this code is index shifting when elements are removed in a for loop when iterating from the left side. so in some cases not all elements that match the condition will be removed. see samples in the attached file: https://sololearn.com/compiler-playground/ctJlID88z6gh/?ref=app
10th Sep 2024, 7:32 PM
Lothar
Lothar - avatar
+ 1
Lothar '?' counts as multiple characters?
10th Sep 2024, 7:46 PM
Igor Matić
Igor Matić - avatar
+ 1
Igor Matić , in a string, `?` is a regular character like a letter or a digit. you can try any other character instead. the issue happens if 2 words < length 5 follow each other.
10th Sep 2024, 8:28 PM
Lothar
Lothar - avatar