How to create a set in Python?

In Python, there are a few ways to create a set. Here are some common methods to create sets:

  1. Using curly braces :
my_set = {1, 2, 3}

In this method, you enclose the elements of the set within curly braces. Note that if you provide duplicate elements, they will be automatically removed since sets only store unique elements.

  1. Using the set() constructor:
my_set = set([1, 2, 3])

Here, you pass a list (or any iterable) to the set() constructor. The constructor converts the iterable into a set.

  1. Using the set() constructor with curly braces :
my_set = set({1, 2, 3})

In this method, you pass the elements directly within curly braces to the set() constructor. This is essentially the same as method 1, but it explicitly uses the set() constructor.

It's important to note that sets are mutable, meaning you can add or remove elements from a set after it is created. However, the elements themselves must be immutable (e.g., numbers, strings, tuples). Sets cannot contain mutable elements like lists or dictionaries.

Here's an example demonstrating the creation of sets using different methods:

# Using curly braces
set1 = {1, 2, 3}
print(set1)  # Output: {1, 2, 3}

# Using the set() constructor with a list
set2 = set([4, 5, 6])
print(set2)  # Output: {4, 5, 6}

# Using the set() constructor with curly braces
set3 = set({7, 8, 9})
print(set3)  # Output: {8, 9, 7}

This example demonstrates various ways to create sets in Python. You can choose the method that best suits your needs and the available input data.

Related Questions You Might Be Interested