2.1 Set and Its Properties
Sets are a special type of collection in programming that helps store unique elements. Simply put, a set is like a basket where you can only put non-repeating items. If you try to put something that's already there, the basket will just ignore it.
Main characteristics of sets:
Uniqueness:
In a set, each element is unique. If you add an element that already exists in the set, it won't be added again.
Unordered:
Unlike lists, elements in a set have no defined order. This means that
you can't access elements by index
.
Mutable:
Sets can be modified—adding and removing elements, but the elements themselves must be immutable (like numbers, strings, or tuples).
2.2 Creating a Set in Python
Let's look at all the ways to create sets in Python so you have a full arsenal of methods to work with them.
Using Curly Braces
The most common way to create a set is by using curly braces {}. Just like with tuples and lists, you simply list the elements inside the braces:
fruit_set = {"apple", "banana", "cherry"}
print(fruit_set) # Output: {"banana", "cherry", "apple"}
Elements can be of different types, but each element must be unique.
fruit_set = {"apple", 1, 3.25}
print(fruit_set) # Output: {1, "apple", 3.25}
Using the set()
Function
The set()
function can be used to create a set from another iterable object like a list, string, or tuple.
From a List
list_to_set = set([1, 2, 3, 4, 4, 5])
print(list_to_set) # Output: {1, 2, 3, 4, 5}
From a String
string_to_set = set("hello")
print(string_to_set) # Output: {"h", "e", "l", "o"}
From a Tuple
tuple_to_set = set((1, 2, 3, 4, 5))
print(tuple_to_set) # Output: {1, 2, 3, 4, 5}
From Another Set
You can create a set from another set, which is useful for making copies.
original_set = {"apple", "banana", "cherry"}
new_set = set(original_set)
print(new_set) # Output: {"banana", "cherry", "apple"}
Empty Set
To create an empty set, use the set()
function. Note that using curly braces {}
will create an empty dictionary (dictionary)
, not a set.
empty_set = set()
print(empty_set) # Output: set()
2.3 List of Methods
Sets in Python have a set of methods that allow for efficient management of data collections. Here are some of the most popular methods of the set
class:
Method | Description |
---|---|
add() |
Adds an element to the set |
remove() |
Removes an element from the set, raises an error if the element is not present |
discard() |
Removes an element from the set, no error if the element is not present |
pop() |
Removes and returns a random element, raises an error if the set is empty |
clear() |
Removes all elements from the set |
union() |
Returns the union of sets |
intersection() |
Returns the intersection of sets |
difference() |
Returns the difference of sets |
symmetric_difference() |
Returns the symmetric difference of sets |
update() |
Adds elements from another set or iterable to the current set |
Below, we'll explore the nuances of all these methods and even a bit more.
GO TO FULL VERSION