What Are Sets in Python? See Examples in detail

Sets in Python are used to store multiple unique values in a single variable. Unlike lists and tuples, sets are unordered, unindexed, and do not allow duplicate elements.

Sets are written using curly braces {}.


Why Sets Are Important

Sets are useful when:

  • You want to store unique values
  • Remove duplicates from data
  • Perform mathematical set operations
  • Check membership efficiently

Example:

numbers = {1, 2, 3, 4}

Creating a Set in Python

fruits = {"apple", "banana", "mango"}
mixed = {1, "Python", True}

Duplicate Values in Sets

Sets automatically remove duplicates.

nums = {1, 2, 2, 3}
print(nums)

Output:

{1, 2, 3}

Accessing Set Items

Since sets are unordered, you cannot access items using indexes. You can iterate using loops.

for fruit in fruits:
    print(fruit)

Adding Items to a Set

fruits.add("orange")
fruits.update(["kiwi", "grapes"])

Removing Items from a Set

fruits.remove("apple")
fruits.discard("banana")
fruits.pop()

Set Operations

Python supports mathematical set operations.

Union

a = {1, 2}
b = {3, 4}
print(a | b)

Intersection

print(a & b)

Difference

print(a - b)

Symmetric Difference

print(a ^ b)

Common Set Methods

MethodDescription
add()Adds item
remove()Removes item
union()Combines sets
intersection()Common items

Conclusion

Sets are powerful for handling unique data and performing fast operations. They are commonly used in data cleaning, comparisons, and membership checks.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *