Page Contents
Executive Page Summary
Sets are one of the built-in data types in Python. They are an unordered collection of unique elements, and they can be used to perform various operations such as union, intersection, and difference. This guide provides an introduction to sets in Python, including their syntax, methods, and common use cases.
To create a set in Python, you can use curly braces {}
or the built-in set()
function. Here's an example:
# Using curly braces
my_set = {'apple', 'banana', 'orange'}
# Using the set() function
my_set = set(['apple', 'banana', 'orange'])
Note that sets are unordered, so the order of the elements may not be preserved.
You can add elements to a set using the add()
method, and you can remove elements using the remove()
method. Here's an example:
my_set = {'apple', 'banana', 'orange'}
# Adding an element
my_set.add('pear')
# Removing an element
my_set.remove('banana')
Sets support various operations such as union, intersection, and difference. Here's an overview of these operations:
Here's an example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Union
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4}
# Intersection
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {2, 3}
# Difference
difference_set = set1.difference(set2)
print(difference_set) # Output: {1}