Unique Elements in 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 find the unique elements in a list, which means we want to remove any duplicates and only keep the distinct values. In this challenge, you will write a function that takes a list as input and returns a new list containing only the unique elements.


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-13739{{"`Unique Elements in List`"}} python/variables_data_types -.-> lab-13739{{"`Unique Elements in List`"}} python/lists -.-> lab-13739{{"`Unique Elements in List`"}} python/tuples -.-> lab-13739{{"`Unique Elements in List`"}} python/function_definition -.-> lab-13739{{"`Unique Elements in List`"}} python/data_collections -.-> lab-13739{{"`Unique Elements in List`"}} python/build_in_functions -.-> lab-13739{{"`Unique Elements in List`"}} end

Unique Elements in List

Write a Python function called unique_elements that takes a list as input and returns a new list containing only the unique elements. Your function should perform the following steps:

  • Create a set from the list to discard duplicated values.
  • Return a list from the set.

Your function should have the following signature:

def unique_elements(li: List) -> List:
def unique_elements(li):
  return list(set(li))
unique_elements([1, 2, 2, 3, 4, 3]) ## [1, 2, 3, 4]

Summary

In this challenge, you have written a Python function that takes a list as input and returns a new list containing only the unique elements. You have learned how to use sets to remove duplicates and how to convert a set back to a list.

Other Python Tutorials you may like