DEV Community 👩‍💻👨‍💻

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

Python Daily Exercise 5: Generate new list by removing unwanted object

Question

Given:

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
Enter fullscreen mode Exit fullscreen mode

Expected Output:

Original list of sting
['Emma', 'Jon', '', 'Kelly', None, 'Eric', '']

After removing empty strings
['Emma', 'Jon', 'Kelly', 'Eric']
Enter fullscreen mode Exit fullscreen mode

My solution

I don't have any clue at first, so I look at the hint and it tell me to use filter() function, or use the for loop and if condition to remove the empty strings from a list

I Search and Learn The filter() Function

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]  
print("Original list of sting")

filtered_list = list(filter(None, str_list))  
print("After removing empty strings")  
print(filtered_list)
Enter fullscreen mode Exit fullscreen mode
  • filter() function has a syntax of filter(function, iterable) and return a iterator, so I cannot just print out the result, need to use a list to include all the element.
  • However I feel using list comprehension is faster, easier and more Pythonic than the filter function,

Or Use List Comprehension

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]  
new_list = [x for x in str_list if x]  

print(new_list)
Enter fullscreen mode Exit fullscreen mode

Other solution

  • Using if loop
str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
res_list = []
for s in str_list:
    # check for non empty string
    if s:
        res_list.append(s)
print(res_list)
Enter fullscreen mode Exit fullscreen mode

algo of the loop:
create an new empty
then iterate the old list
check the object's truth is false
(empty string and None are considered False in default)
if the object is True add to new list

My reflection

  • I cannot figure out how to use the if loop at first, as i don't remember the default truth value of an object.

Credit

Top comments (0)

🌚 Life is too short to browse without dark mode