Unique List Combination in Python

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 combine two lists and remove any duplicates to get a new list containing all the unique elements. This process is called list union. In this challenge, you will be asked to write a Python function that takes two lists as input and returns a new list containing all the unique elements from both lists.


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/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-13738{{"Unique List Combination in Python"}} python/comments -.-> lab-13738{{"Unique List Combination in Python"}} python/lists -.-> lab-13738{{"Unique List Combination in Python"}} python/tuples -.-> lab-13738{{"Unique List Combination in Python"}} python/function_definition -.-> lab-13738{{"Unique List Combination in Python"}} python/build_in_functions -.-> lab-13738{{"Unique List Combination in Python"}} python/data_collections -.-> lab-13738{{"Unique List Combination in Python"}} end

List Union

Write a Python function called list_union(a, b) that takes two lists as input and returns a new list containing all the unique elements from both lists. Your function should perform the following steps:

  1. Combine the two input lists a and b into a single list.
  2. Remove any duplicates from the combined list.
  3. Return the new list containing all the unique elements.

Your function should not modify the input lists a and b.

def union(a, b):
  return list(set(a + b))
union([1, 2, 3], [4, 3, 2]) ## [1, 2, 3, 4]

Summary

In this challenge, you have learned how to write a Python function that takes two lists as input and returns a new list containing all the unique elements from both lists. You have also learned how to combine two lists, remove duplicates, and return a new list.