Wednesday, January 22, 2025
HomeProgrammingWhat is Python Sets?

What is Python Sets?

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:

  1. 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.
  2. 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.
  3. Mutable: You can add or remove elements from a set after it is created.
  4. 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.
See also  How do I split the definition of a long string over multiple lines in Python?

Operations on Sets:

  1. 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}
    
  2. Removing Elements:
    • You can remove an element using remove() or discard(). The remove() method raises a KeyError if the element is not found, while discard() 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)
    
  3. 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
    
  4. 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
    

Set Operations:

Sets support various operations like union, intersection, difference, and symmetric difference.

  1. Union (| or union()): 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}
    
  2. Intersection (& or intersection()): 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}
    
  3. Difference (- or difference()): 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}
    
  4. Symmetric Difference (^ or symmetric_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}
    
  5. Subset and Superset:
    • Subset (<= or issubset()): 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 (>= or issuperset()): 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
    

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x