How To Print Only True Values In Python

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 sets set() 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:

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:

Output:

[1, 'hello', [1, 2]]

This example provides the same output as the one using filter() function.

Full Code

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.