0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert List to Set - Simple Guide

You can convert a list to a set in Python by using the set() function like this: my_set = set(my_list).
📋

Examples

Input[1, 2, 3]
Output{1, 2, 3}
Input[1, 2, 2, 3, 3, 3]
Output{1, 2, 3}
Input[]
Outputset()
🧠

How to Think About It

To convert a list to a set, think about removing duplicates and collecting unique items. Using the set() function takes the list and returns a new collection with only unique elements, ignoring order.
📐

Algorithm

1
Get the input list.
2
Apply the <code>set()</code> function to the list.
3
Return or store the resulting set.
💻

Code

python
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)
print(my_set)
Output
{1, 2, 3}
🔍

Dry Run

Let's trace converting [1, 2, 2, 3, 3, 3] to a set.

1

Start with list

[1, 2, 2, 3, 3, 3]

2

Convert list to set

set([1, 2, 2, 3, 3, 3])

3

Resulting set

{1, 2, 3}

StepValue
Initial list[1, 2, 2, 3, 3, 3]
After set(){1, 2, 3}
💡

Why This Works

Step 1: Using set() removes duplicates

The set() function creates a collection of unique elements from the list, automatically removing repeated items.

Step 2: Sets are unordered

Unlike lists, sets do not keep the order of elements, so the output may appear in any order.

Step 3: Result is a set object

The result is a set type, which supports fast membership tests and unique storage.

🔄

Alternative Approaches

Using a loop to add elements to a set
python
my_list = [1, 2, 2, 3, 3, 3]
my_set = set()
for item in my_list:
    my_set.add(item)
print(my_set)
This method is more manual and less concise but shows how sets build unique collections step-by-step.
Using dictionary keys (Python 3.7+ preserves order)
python
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(dict.fromkeys(my_list))
print(my_set)
This preserves the order of first occurrences but is more complex than using set() directly.

Complexity: O(n) time, O(n) space

Time Complexity

Converting a list to a set takes O(n) time because it processes each element once to check uniqueness.

Space Complexity

The new set requires O(n) space to store unique elements, where n is the number of elements in the list.

Which Approach is Fastest?

Using the built-in set() function is the fastest and simplest way compared to manual loops or dictionary keys.

ApproachTimeSpaceBest For
set() functionO(n)O(n)Simple and fast conversion
Loop with add()O(n)O(n)Learning how sets work internally
dict.fromkeys()O(n)O(n)Preserving order of first occurrences
💡
Use set() to quickly remove duplicates from a list.
⚠️
Trying to convert a list with unhashable items (like other lists) to a set will cause an error.