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

Time:11-12

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?

CodePudding user response:

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 != ""]

CodePudding user response:

Update: because you say (How should I revise this code by not using list comprehension or other methods?) I send this answer otherwise other answers are better for the future.

You need to increase the index, here in your code x =1 like below:

list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = []
x = 0
while x < len(list1):
    if len(list1[x]) > 0:
        list2.append(list1[x])
    x  = 1
print(list2)

Output:

['apple', 'pear', 'strawberry', 'orange', 'grapes', 'watermelon']

CodePudding user response:

Assuming that this is your desired output:

['apple', 'pear', 'strawberry', 'orange', 'grapes', 'watermelon']

Here's a way without using builtins or list comprehensions:

list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]

list2 = []
for x in list1:
    x and list2.append(x)

Assuming are allowed to use builtins such as filter:

list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = list(filter(None, list1))
  • Related