list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = []
x = 0
while x < len(list1):
if len(list1[x]) > 0:
list2.append(list1[x])
print(list2)
I tried to run this code, but it seems that it doesn't work. How should I revise this code by not using list comprehension or other methods?
Update: Just noticed that you do not want to use a different method, so this answer is for future visitors only.
You can implement the same functionality in a single line:
list2 = list(filter(None, list1))
Note that this will also remove elements that are equal to 0, False, or None. A closer implementation could be with a list comprehension:
list2 = [i for i in list1 if i != ""]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With