In Python, a set is an unordered collection of unique elements. Sets are one of the built-in data types in Python and are part of the collection of data types that also includes lists, tuples, and dictionaries.
Key Characteristics of Sets:
- Unordered: The items in a set do not have any particular order. When you iterate over a set, the items may appear in a different order each time.
- Unique Elements: A set only stores unique elements. If you try to add duplicate values, only one instance of that value will be stored in the set.
- Mutable: You can add or remove elements from a set after it is created.
- No Indexing: Unlike lists and tuples, sets do not support indexing, slicing, or other sequence-like behavior.
Creating a Set:
You can create a set by placing the elements inside curly braces {}
or by using the set()
constructor.
Example 1: Creating a Set with Curly Braces
# Creating a set with curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
Example 2: Creating a Set using the set()
Constructor
# Creating a set using the set() constructor
my_set = set([1, 2, 3, 4, 5])
print(my_set) # Output: {1, 2, 3, 4, 5}
Note:
- If you pass a list or another iterable to the
set()
constructor, it will remove any duplicate values automatically. - Sets cannot contain mutable data types like lists or dictionaries.
Operations on Sets:
- Adding Elements:
- You can add an element to a set using the
add()
method.
my_set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4}
- You can add an element to a set using the
- Removing Elements:
- You can remove an element using
remove()
ordiscard()
. Theremove()
method raises aKeyError
if the element is not found, whilediscard()
will not raise an error.
my_set = {1, 2, 3, 4} my_set.remove(3) # Removes 3 from the set print(my_set) # Output: {1, 2, 4} my_set.discard(5) # Does nothing as 5 is not in the set print(my_set) # Output: {1, 2, 4}
- You can also remove an arbitrary element using
pop()
, but remember that sets are unordered, so you can’t specify which element to remove.
popped_item = my_set.pop() print(popped_item) # Output: any one item, because the set is unordered print(my_set)
- You can remove an element using
- Checking Membership:
- You can check if an element is in a set using the
in
keyword.
my_set = {1, 2, 3, 4} print(3 in my_set) # Output: True print(5 in my_set) # Output: False
- You can check if an element is in a set using the
- Set Length:
- You can find the number of elements in a set using the
len()
function.
my_set = {1, 2, 3, 4} print(len(my_set)) # Output: 4
- You can find the number of elements in a set using the
Set Operations:
Sets support various operations like union, intersection, difference, and symmetric difference.
- Union (
|
orunion()
): Combines elements from two sets, removing duplicates.set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 | set2) # Output: {1, 2, 3, 4, 5} # or print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
- Intersection (
&
orintersection()
): Returns elements that are present in both sets.set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 & set2) # Output: {3} # or print(set1.intersection(set2)) # Output: {3}
- Difference (
-
ordifference()
): Returns elements that are in the first set but not in the second.set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 - set2) # Output: {1, 2} # or print(set1.difference(set2)) # Output: {1, 2}
- Symmetric Difference (
^
orsymmetric_difference()
): Returns elements that are in either of the sets, but not in both.set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 ^ set2) # Output: {1, 2, 4, 5} # or print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
- Subset and Superset:
- Subset (
<=
orissubset()
): Checks if all elements of one set are in another.
set1 = {1, 2} set2 = {1, 2, 3, 4} print(set1 <= set2) # Output: True # or print(set1.issubset(set2)) # Output: True
- Superset (
>=
orissuperset()
): Checks if one set contains all elements of another.
set1 = {1, 2, 3, 4} set2 = {1, 2} print(set1 >= set2) # Output: True # or print(set1.issuperset(set2)) # Output: True
- Subset (
Example of Using Sets in Python:
# Example of a Python Set
fruits = {"apple", "banana", "cherry", "apple"} # 'apple' will only appear once
print(fruits) # Output: {'banana', 'cherry', 'apple'}
# Adding and removing elements
fruits.add("orange") # Add a new fruit
print(fruits) # Output: {'banana', 'cherry', 'apple', 'orange'}
fruits.remove("banana") # Remove a fruit
print(fruits) # Output: {'cherry', 'apple', 'orange'}
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# Difference
print(set1 - set2) # Output: {1, 2}
# Symmetric Difference
print(set1 ^ set2) # Output: {1, 2, 4, 5}
Conclusion:
Sets are powerful and efficient data structures in Python that help manage collections of unique items. They are particularly useful for operations involving membership tests, uniqueness checks, and performing mathematical set operations like union, intersection, and difference.