Remove Falsy Values in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you need to write a Python function that removes falsy values from a list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/variables_data_types -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/booleans -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/lists -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/tuples -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/function_definition -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/data_collections -.-> lab-13605{{"`Remove Falsy Values in Python`"}} python/build_in_functions -.-> lab-13605{{"`Remove Falsy Values in Python`"}} end

Compact List

Write a function compact(lst) that takes a list as an argument and returns a new list with all falsy values removed. Falsy values include False, None, 0, and "".

To solve this problem, you can use the filter() function to filter out falsy values from the list.

def compact(lst):
  return list(filter(None, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) ## [ 1, 2, 3, 'a', 's', 34 ]

Summary

In this challenge, you have learned how to remove falsy values from a list using the filter() function in Python.

Other Python Tutorials you may like