Check if List Elements are Identical

PythonPythonBeginner
Practice Now

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

Introduction

In Python, you can easily check if all elements in a list are identical using a simple function. In this challenge, you will be tasked with creating a function that checks if all elements in a list are identical.


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-13585{{"`Check if List Elements are Identical`"}} python/variables_data_types -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/booleans -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/lists -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/tuples -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/function_definition -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/data_collections -.-> lab-13585{{"`Check if List Elements are Identical`"}} python/build_in_functions -.-> lab-13585{{"`Check if List Elements are Identical`"}} end

Check if List Elements are Identical

Write a function all_equal(lst) that takes a list as an argument and returns True if all elements in the list are identical, and False otherwise.

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

  1. Use set() to eliminate duplicate elements in the list.
  2. Use len() to check if the length of the set is 1.
  3. If the length of the set is 1, return True. Otherwise, return False.
def all_equal(lst):
  return len(set(lst)) == 1
all_equal([1, 2, 3, 4, 5, 6]) ## False
all_equal([1, 1, 1, 1]) ## True

Summary

In this challenge, you learned how to check if all elements in a list are identical using a simple function. You can use this function to quickly determine if a list contains only identical elements.

Other Python Tutorials you may like