python
  1. python-sets

Python Sets

Sets are a data type in Python that store unique elements in no particular order. Sets are created with curly braces {} or with the set() constructor.

Syntax

# Creating a set
set1 = {1, 2, 3, 4, 5}

# Adding elements to a set
set1.add(6)

# Removing elements from a set
set1.remove(3)

# Intersection of two sets
set2 = {4, 5, 6, 7, 8}
set3 = set1.intersection(set2)

# Union of two sets
set4 = set1.union(set2)

# Difference of two sets
set5 = set1.difference(set2)

Example

# Create a set
set1 = {1, 2, 3, 4, 5}

# Print the set
print(set1)

# Add an element to the set
set1.add(6)

# Print the updated set
print(set1)

# Remove an element from the set
set1.remove(3)

# Print the updated set
print(set1)

# Intersection of two sets
set2 = {4, 5, 6, 7, 8}
set3 = set1.intersection(set2)

# Print the intersection set
print(set3)

# Union of two sets
set4 = set1.union(set2)

# Print the union set
print(set4)

# Difference of two sets
set5 = set1.difference(set2)

# Print the difference set
print(set5)

Output

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}
{4, 5}
{1, 2, 4, 5, 6, 7, 8}
{1, 2, 6}

Explanation

  1. We create a set set1 with five elements.
  2. We add an element 6 to the set set1 using the add() method.
  3. We remove the element 3 from the set set1 using the remove() method.
  4. We find the intersection of set1 and set2 using the intersection() method and store the result in set3.
  5. We find the union of set1 and set2 using the union() method and store the result in set4.
  6. We find the difference of set1 and set2 using the difference() method and store the result in set5.

Use

Sets can be used to store unique elements and perform operations such as intersection, union, and difference on them. They are also useful for checking if an element is present in a collection.

Important Points

  1. Sets are mutable, meaning they can be changed after they are created.
  2. Sets do not allow duplicate values.
  3. Set elements are not ordered, meaning they may appear in a different order when printed or iterated over.
  4. The add() method adds a single element to a set, while the update() method can be used to add multiple elements at once.
  5. The remove() method removes a single element from a set, while the discard() method removes an element if it is present, but does not raise an error if it is not.
  6. The union(), intersection(), and difference() methods return new sets without modifying the original sets.

Summary

Sets are a useful data type in Python for storing unique elements and performing operations such as intersection, union, and difference. They are created using curly braces or the set() constructor, and offer methods for adding, removing, and manipulating elements. Sets do not allow duplicate values and are not ordered.

Published on: