Geek Slack

Start creating your course and become a part of GeekSlack.

Introduction to Python
About Lesson



Python Sets


Python Sets

A set in Python is an unordered collection of unique items. Sets are mutable, meaning you can add or remove elements from them.

1. Creating Sets

You can create sets using curly braces {} or the set() constructor.

Example:

numbers = {1, 2, 3, 4, 5}
fruits = {'apple', 'banana', 'orange'}
empty_set = set()

2. Accessing Elements

Since sets are unordered, you cannot access elements by index. However, you can check for membership.

Example:

numbers = {1, 2, 3, 4, 5}
is_present = 3 in numbers    # True

3. Adding and Removing Elements

You can add elements to a set using the add() method and remove elements using the remove() or discard() method.

Example:

numbers = {1, 2, 3, 4, 5}
numbers.add(6)
numbers.remove(3)

4. Set Operations

Python sets support various operations such as union, intersection, difference, and symmetric difference.

Example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union = set1 | set2            # {1, 2, 3, 4, 5}
intersection = set1 & set2     # {3}
difference = set1 - set2       # {1, 2}
symmetric_difference = set1 ^ set2  # {1, 2, 4, 5}

Conclusion

Sets are useful for storing unique elements and performing set operations efficiently. Understanding how to create, add, remove, and perform set operations is essential for working with sets in Python.

Join the conversation