Find Common Elements in Python Lists | Challenge

PythonPythonBeginner
Practice Now

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

Introduction

In Python, you can easily find the common elements between two lists using the set intersection operation. In this challenge, you will be asked to write a function that takes two lists as input and returns a new list containing only the elements that are present in both input lists.


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/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-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/variables_data_types -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/lists -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/tuples -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/function_definition -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/data_collections -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} python/build_in_functions -.-> lab-13132{{"`Find Common Elements in Python Lists | Challenge`"}} end

List Intersection Challenge

Problem

Write a function list_intersection(a, b) that takes two lists a and b as input and returns a new list containing only the elements that are present in both a and b. If there are no common elements, the function should return an empty list.

Example

list_intersection([1, 2, 3], [4, 3, 2]) ## [2, 3]
list_intersection([1, 2, 3], [4, 5, 6]) ## []
list_intersection([1, 2, 3], [3, 3, 2]) ## [2, 3]

Summary

To solve this challenge, you need to convert the input lists into sets and then use the set intersection operation to find the common elements. Finally, you need to convert the resulting set back into a list and return it.

Other Python Tutorials you may like