Creating a New List with Multiple Occurrences Removed Using the Set() Function in Python

Creating a New List with Multiple Occurrences Removed Using the Set() Function in Python

ECX 30 Days of Code:

Day 1

List to Set

Task

Create a function that takes in a list as input, and returns (and prints) a new list with all repetitions reduced to one appearance alone, as output. e.g.; f(["a", "b", "a", "a", 3, 3, 2, "hello", "b"]) => ["a", "b", 3, 2, "hello"]

Discussion

Python has an inbuilt function set() which takes a list as arguments and returns a set of unique items (i.e., multiple occurrences of items are reduced to one occurrence).

My Approach

First, we create a list which would be the argument of the function, set_function(). We then define the set_function(). Next, create a variable called set_list and assign it to have a new set of unique items using the set() function.

# List
ecx_items = ["a", "b", "a", "a", 3, 3, 2, "hello", "b"]


def set_function(list_items):
    """Takes a list and prints a new list with repetitions removed"""
    set_list = set(list_items)

    print(list(set_list))


# Function call
set_function(ecx_items)

Next we print out a new list (by converting the set of items to a list) using the list() function. If we use print(set_list), we get;

{'a', 2, 3, 'b', 'hello'}

But when we use the list() function, and we call the function, set_function() function with ecx_items as its argument, we get;

[2, 3, 'b', 'a', 'hello']

The difference between the two outputs displayed is that the set() function makes use of curly braces {}, while the list() function makes use of square brackets []. There you have it. We have been able to eliminate multiple occurrences of list items using the set() function.

Run the code on Replit.