Remove Falsy Values in Python List

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-13073{{"`Remove Falsy Values in Python List`"}} python/variables_data_types -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/booleans -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/lists -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/tuples -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/function_definition -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/data_collections -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} python/build_in_functions -.-> lab-13073{{"`Remove Falsy Values in Python List`"}} end

Compact List

Problem

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.

Example

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