What are Python sets?
Python sets are unordered collections of unique elements. This means that the elements in a set are not in any particular order, and each element can only appear in the set once. Sets are created using curly braces ({}) and can contain any type of data, including integers, floats, strings, lists, and dictionaries.
How to create a Python set
To create a Python set, you simply enclose the elements of the set in curly braces. For example:
Python
my_set = {1, 2, 3, 4, 5}
This code creates a set containing the numbers 1 through 5.
How to access items in a Python set
Since sets are unordered, there is no way to access specific items in a set by index. However, you can use the in operator to check if an item is contained in a set. For example:
Python
print(1 in my_set) # Outputs True
print(6 in my_set) # Outputs False
You can also use the &, |, and - operators to perform set operations on two sets, such as union, intersection, and difference. For example:
Python
my_set2 = {6, 7, 8, 9, 10}
# Union of two sets
my_set_union = my_set | my_set2
# Intersection of two sets
my_set_intersection = my_set & my_set2
# Difference of two sets
my_set_difference = my_set - my_set2
How to iterate over a Python set
To iterate over a Python set, you can use the for loop. The for loop iterates over each item in the set and executes a block of code for each item. For example:
Python
for item in my_set:
print(item)
This code will print each item in the set to the console in an arbitrary order.
Python set methods
There are a few Python set methods that can be used to perform various tasks on sets, such as adding and removing items from a set, checking if a set is empty, and finding the union, intersection, and difference of two sets.
Here are some examples of Python set methods:
Here are some additional tips for using Python sets: