str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
str_list = [x for x in str_list if x]
print(str_list)
CodePudding user response:
Python supports the concepts of "truthy," meaning a value treated as logically true, and "falsey," a value logically treated as false. As it turns out, empty string is falsey, so the if x
condition in the list comprehension will exclude empty string values.
CodePudding user response:
Here, checking if x
is implicitly looking at bool(x)
. Specifically, notice that when x
is an empty string, bool(x)
is false: we say that it is "falsy." You can see this for yourself interactively:
>>> bool("Emma")
True
>>> bool("")
False
>>>
This list comprehension effectively filters out these "falsy" values, or in this case, empty strings.
For more about common truth values and how to customize your own, see the Python docs.