Unique List Combination in Python

Beginner

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.

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.