Python Sets
Here’s an example of creating a set:
python
my_set = {1, 2, 3, 4, 5}
In this example, my_set
is a set containing the numbers 1, 2, 3, 4, and 5.
Sets automatically eliminate duplicate elements, so if you try to add a duplicate value to a set, it will be ignored. For example:
python
my_set = {1, 2, 3, 3, 4, 4, 5}
print(my_set)
Output:
{1, 2, 3, 4, 5}
Sets support various operations such as union, intersection, difference, and symmetric difference. These operations can be performed using built-in methods or operators. Here are some common set operations:
- Union:
set1 | set2
orset1.union(set2)
returns a new set with all elements from bothset1
andset2
. - Intersection:
set1 & set2
orset1.intersection(set2)
returns a new set with elements present in bothset1
andset2
. - Difference:
set1 - set2
orset1.difference(set2)
returns a new set with elements fromset1
that are not inset2
. - Symmetric Difference:
set1 ^ set2
orset1.symmetric_difference(set2)
returns a new set with elements that are in eitherset1
orset2
, but not both.
Sets are also useful for checking membership and performing fast membership testing. You can use the in
operator to check if an element is present in a set. For example:
python
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # Output: True
print(6 in my_set) # Output: False
Sets can be modified by adding or removing elements using methods such as add()
, remove()
, discard()
, pop()
, and clear()
. For example:
python
my_set = {1, 2, 3}
my_set.add(4) # Add a single element
my_set.update([5, 6]) # Add multiple elements
my_set.remove(3) # Remove an element
my_set.discard(2) # Remove an element if it exists, or do nothing if it doesn't
my_set.pop() # Remove and return an arbitrary element
my_set.clear() # Remove all elements from the set
Sets are particularly useful when you need to perform operations like finding unique elements, removing duplicates, or checking membership efficiently.