Skip to main content

How to convert a list to a set in Python

How to convert a list to a set in Python.

Here is a step-by-step tutorial on how to convert a list to a set in Python:

1: Create a list

Start by creating a list in Python. A list is an ordered collection of elements enclosed in square brackets ([]). For example, let's create a list of numbers:

numbers = [1, 2, 3, 4, 5]

2: Convert the list to a set

To convert the list to a set, you can use the set() function in Python. The set() function takes an iterable (in this case, our list) as an argument and returns a new set containing all the unique elements from the iterable. Here's how you can convert the numbers list to a set:

numbers_set = set(numbers)

3: Access and print the set

Now that you have converted the list to a set, you can access and print the set elements. Sets are unordered collections, so the order of elements may vary each time you run the code. You can use a loop or simply print the set directly. Here's an example:

for num in numbers_set:
print(num)

Alternatively, you can directly print the set without using a loop:

print(numbers_set)

4: Verify the type

Finally, it's a good practice to verify the type of the converted object. You can use the type() function in Python to check the type. Here's an example:

print(type(numbers_set))

This will output class 'set', confirming that the list has been successfully converted to a set.

That's it! You have now learned how to convert a list to a set in Python.