Check for Duplicates in List Function

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 has any duplicate elements. In this challenge, you will write a Python function to check 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-13586{{"`Check for Duplicates in List Function`"}} python/variables_data_types -.-> lab-13586{{"`Check for Duplicates in List Function`"}} python/booleans -.-> lab-13586{{"`Check for Duplicates in List Function`"}} python/lists -.-> lab-13586{{"`Check for Duplicates in List Function`"}} python/function_definition -.-> lab-13586{{"`Check for Duplicates in List Function`"}} python/data_collections -.-> lab-13586{{"`Check for Duplicates in List Function`"}} python/build_in_functions -.-> lab-13586{{"`Check for Duplicates in List Function`"}} end

Check for Duplicates in List Function

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

To solve this problem, you can follow these steps:

  1. Convert the list to a set to remove duplicates.
  2. Compare the length of the set with the length of the original list.
  3. If the lengths are equal, then the list has no duplicates, otherwise it has duplicates.
def all_unique(lst):
  return len(lst) == len(set(lst))
x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]
all_unique(x) ## True
all_unique(y) ## False

Summary

In this challenge, you learned how to check for duplicates in a list using Python. You can use this function to ensure that your lists only contain unique elements.

Other Python Tutorials you may like