Why Would You Assign or Copy a list in Python to be a set?

Problem scenario
You are trying to understand some code. You see a variable in Python that represents a list being cast to a set.

You see something like this in a Python program:

example = [1, 1, 2, 2, 3, 3]
new_example = set(example)

You are curious why this would be done.

From the IDE you do (and see) the following:

>>> example = [1, 1, 2, 2, 3, 3]
>>> print(example)
[1, 1, 2, 2, 3, 3]
>>> new_example = set(example)
>>> print(new_example)
{1, 2, 3}

What would be the benefit of this?

Answer
A set has no duplicate values. It is a quick way to eliminate duplicates.

Leave a comment

Your email address will not be published. Required fields are marked *