This tutorial will discuss how to create a set in Python. Sets are a collection of unique elements, which are unordered, mutable, and do not support indexing or slicing.
In Python, the set
data structure is used to store sets. It’s an efficient way to handle large data sets and perform operations like union, intersection, and differences between sets.
1. Creating an Empty Set
To create an empty set, you need to use the set()
function. Using curly brackets {}
will create an empty dictionary instead of an empty set.
1 |
empty_set = set() |
2. Creating a Set with Values
To create a set with initial values, simply put the values inside curly brackets {}
separated by commas.
1 |
values_set = {1, 2, 3, 4, 5} |
3. Creating a Set from a List or Tuple
In case you have a list or tuple and want to create a set from its unique elements, you can use the set()
function.
1 2 |
my_list = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1] my_set = set(my_list) |
The same method applies for tuples:
1 2 |
my_tuple = (1, 2, 3, 4, 5, 5, 4, 3, 2, 1) my_set = set(my_tuple) |
4. Set Comprehensions
Just like list comprehensions, you can use set comprehensions to create sets. This method is usually more efficient and provides more concise syntax.
1 |
squared_set = {x**2 for x in range(1, 6)} |
In this example, the squared_set
will be a set containing the squares of numbers from 1 to 5.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Creating an empty set empty_set = set() # Creating a set with values values_set = {1, 2, 3, 4, 5} print(values_set) # Creating a set from a list my_list = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1] my_set = set(my_list) print(my_set) # Creating a set from a tuple my_tuple = (1, 2, 3, 4, 5, 5, 4, 3, 2, 1) my_set = set(my_tuple) print(my_set) # Set comprehensions squared_set = {x**2 for x in range(1, 6)} print(squared_set) |
Output
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5} {1, 2, 3, 4, 5} {1, 4, 9, 16, 25}
Conclusion
Now, you should be able to create sets in Python using different methods. Sets are a powerful data structure that can simplify many tasks requiring the manipulation and analysis of large amounts of data.
With sets, you can easily perform operations like union, intersection, or difference between data sets, making them a valuable tool for any Python programmer.