Question
Given:
str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
Expected Output:
Original list of sting
['Emma', 'Jon', '', 'Kelly', None, 'Eric', '']
After removing empty strings
['Emma', 'Jon', 'Kelly', 'Eric']
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)
- 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)
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)
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
- exercise form Pynative
Top comments (0)