Ticker

6/recent/ticker-posts

Set in Python

Set in Python

Introduction: 

A set is an unordered collection of unique elements in Python. It is commonly used to store and manipulate a group of distinct items. Sets are mutable, meaning their elements can be added, removed, or modified after creation. In this documentation, we'll cover the basics of sets in Python, how to create them, perform common operations, and provide code examples for better understanding.

Creating a Set:
To create a set in Python, you can use curly braces {} or the built-in set() function. If you want to initialize an empty set, use set().

python
# Using curly braces
my_set = {1, 2, 3, 4}

# Using set() function
another_set = set([4, 5, 6, 7])

Adding Elements:
You can add elements to a set using the add() method.

python
fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')

Removing Elements:
Elements can be removed from a set using the remove() or discard() methods. The main difference is that remove() will raise a KeyError if the element is not found, whereas discard() will not raise any error.

python
numbers = {1, 2, 3, 4}
numbers.remove(2)
numbers.discard(5) # No error if 5 is not present

Set Operations:
Python sets support various operations like union, intersection, difference, and symmetric difference.

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

# Union
union_set = set1 | set2

# Intersection
intersection_set = set1 & set2

# Difference
difference_set = set1 - set2

# Symmetric Difference
symmetric_difference_set = set1 ^ set2

Iterating through a Set:
You can use a for loop to iterate through the elements of a set.

python
colors = {'red', 'green', 'blue'}
for color in colors:
print(color)

Membership Testing:
You can check if an element exists in a set using the in keyword.

python
fruits = {'apple', 'banana', 'orange'}
print('banana' in fruits) # Output: True
print('grape' in fruits) # Output: False

Conclusion:
Sets in Python are a powerful data structure for handling unique collections of items. They provide various operations for manipulation and make it easy to work with distinct elements. Understanding sets will help you efficiently solve problems that require handling unique values.

Post a Comment

0 Comments