In this tutorial, you will learn how to print only true values in Python. This is useful when you need to filter out false or unwanted elements from a list, dictionary, or other data structures. By the end of this tutorial, you’ll know how to use the built-in filter()
function and list comprehensions to achieve this.
Step 1: Understand True and False Value concepts in Python
In Python, all objects have a truthiness value associated with them. The following are some examples of truthy and falsy values:
- Numeric 0 or 0.0 are considered falsy, while other numeric values are truthy.
- The empty string
''
is falsy, while non-empty strings are truthy. - None is considered falsy.
- Empty data structures such as lists
[]
, dictionaries{}
, and setsset()
are falsy, while non-empty data structures are truthy.
Keep this in mind when working with Python objects and their associated truthy or falsy values.
Step 2: Using filter() function to print only true values
The filter()
function is a built-in Python function used to filter out elements from an iterable based on a given condition. You can use this to filter out all falsy elements by providing None
as the filtering function.
Here’s a simple example:
1 2 3 4 5 6 |
values_list = [1, 0, 'hello', '', None, [1, 2], []] # Filter out falsy values using filter() true_values_list = list(filter(None, values_list)) print(true_values_list) |
Output:
[1, 'hello', [1, 2]]
In this example, 0, empty string ''
, and None
are filtered out, leaving only the true values in true_values_list
.
Step 3: Using list comprehensions to print only true values
You can also use list comprehensions to filter out false values. The idea is to iterate over the list and only include the element in the new list if the element evaluates to True. Here’s how you can do this:
1 2 3 4 5 6 |
values_list = [1, 0, 'hello', '', None, [1, 2], []] # Filter out false values using list comprehensions true_values_list = [val for val in values_list if val] print(true_values_list) |
Output:
[1, 'hello', [1, 2]]
This example provides the same output as the one using filter()
function.
Full Code
1 2 3 4 5 6 7 8 9 |
values_list = [1, 0, 'hello', '', None, [1, 2], []] # Using filter() function to get true values true_values_list_filter = list(filter(None, values_list)) print(true_values_list_filter) # Using list comprehensions to get true values true_values_list_comprehension = [val for val in values_list if val] print(true_values_list_comprehension) |
Output
[1, 'hello', [1, 2]] [1, 'hello', [1, 2]]
Conclusion
In this tutorial, you’ve learned how to print only true values in Python using the built-in filter()
function and list comprehensions. You can apply these techniques to filter out false or unwanted elements from a variety of Python data structures, making your code more efficient and clean.