Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get rid of an empty string with using while loop? (python)

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?

like image 373
yopangyo Avatar asked Dec 30 '25 17:12

yopangyo


1 Answers

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 != ""]
like image 104
Selcuk Avatar answered Jan 02 '26 06:01

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!