Check for Duplicates in a List

PythonPythonBeginner
Practice Now

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

Introduction

In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to check if a list contains duplicate values. In this challenge, you will write a function that checks if a list has any duplicates.


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/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-13651{{"`Check for Duplicates in a List`"}} python/variables_data_types -.-> lab-13651{{"`Check for Duplicates in a List`"}} python/booleans -.-> lab-13651{{"`Check for Duplicates in a List`"}} python/lists -.-> lab-13651{{"`Check for Duplicates in a List`"}} python/function_definition -.-> lab-13651{{"`Check for Duplicates in a List`"}} python/data_collections -.-> lab-13651{{"`Check for Duplicates in a List`"}} python/build_in_functions -.-> lab-13651{{"`Check for Duplicates in a List`"}} end

Check for Duplicates in a List

Write a Python function called has_duplicates(lst) that takes a list as an argument and returns True if the list contains any duplicates, and False otherwise.

To solve this problem, you can use the following steps:

  1. Use the set() function to remove duplicates from the list.
  2. Compare the length of the original list with the length of the set. If they are the same, then there are no duplicates. If they are different, then there are duplicates.
def has_duplicates(lst):
  return len(lst) != len(set(lst))
x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5]
has_duplicates(x) ## True
has_duplicates(y) ## False

Summary

In this challenge, you learned how to check for duplicates in a list using Python. You can use the set() function to remove duplicates and compare the length of the original list with the length of the set to determine if there are any duplicates.

Other Python Tutorials you may like