Python sets

In Python, a set is a collection data type that stores unordered, unique elements. It is useful when you need to eliminate duplicate values, perform mathematical set operations (like unions, intersections, etc.), or manage a collection of unique items efficiently.

Creating a Set

Creating a set in Python can be done using curly braces {} or the set() function. Sets are useful for storing unique, unordered elements.

1. Using Curly Braces {}

You can create a set directly by placing items inside curly braces:


# Creating a set with curly braces
data_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

2. Using the set() Function

You can also create a set using the set() function, especially helpful when creating a set from other iterables like lists, tuples, or strings.


# Creating a set from a list
data_set = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

# Creating a set from a string (breaks it into unique characters)
char_set = set("python")
print(char_set)  # Output: {'p', 'y', 't', 'h', 'o', 'n'}

Note: To create an empty set, you must use set() because {} initializes an empty dictionary.