Find Common Elements in Python Lists

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

List Intersection

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.

def intersection(a, b):
  _a, _b = set(a), set(b)
  return list(_a & _b)
intersection([1, 2, 3], [4, 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