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

List Union Challenge

Problem

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.

Example

list_union([1, 2, 3], [4, 3, 2]) ## [1, 2, 3, 4]
list_union(['apple', 'banana', 'orange'], ['pear', 'banana', 'kiwi']) ## ['apple', 'banana', 'orange', 'pear', 'kiwi']

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.

Other Python Tutorials you may like