Check for Duplicates in List Function | Challenge

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

Check for Duplicates in List Function

Problem

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.

Example

has_duplicates([1, 2, 3, 4, 5]) ## False
has_duplicates([1, 2, 3, 4, 5, 5]) ## True
has_duplicates(['apple', 'banana', 'orange', 'banana']) ## True
has_duplicates([]) ## 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