DEV Community

priyaganth k
priyaganth k

Posted on

Python - {Set}

set{}

It can be denoted as curly braces{1,2,3} with value. It is a mutable data type . Its used to store multiple item in single variable.

Mutable > Can change or modify the value once created .
Immutable > Cannot change or modify the value once defined.

In sets there will be no duplicate value and the value can be unordered.

Common operations

s.add(4) # To add value
s.remove(2) # To remove the value in set
s.discard(99) # safe remove — no error if missing
s.pop() # Remove & return values from collection
s.clear() # Clear all the values from the set

Example

set = {1, 2, 3}

print("values:", set)

set.add(4)
print("Add 4:", set)

set.remove(2)
print("Remove 2:", set)

set.discard(99)
print("Discard 99:", set)

print("Pop value:", set.pop())
print("After pop:", set)

set.clear()
print("After clear:", set)
Enter fullscreen mode Exit fullscreen mode

Output:

value: {1, 2, 3}
Add 4: {1, 2, 3, 4}
Remove 2: {1, 3, 4}
Discard 99: {1, 3, 4}
Pop value: 1
After pop: {3, 4}
After clear: set()

set operations:

if a & b are
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

example code

python_students = {"Priya", "Ravi", "Anu"}
sql_students = {"Anu", "Ravi", "Kiran"}

# Intersection
print("Students in both courses:", python_students & sql_students)

# Union
print("All students:", python_students | sql_students)

# Difference
print("Students only in Python:", python_students - sql_students)

# Symmetric Difference
print("Students in only one course:", python_students ^ sql_students)
Enter fullscreen mode Exit fullscreen mode

output

Students in both courses: {'Anu', 'Ravi'}
All students: {'Priya', 'Ravi', 'Anu', 'Kiran'}
Students only in Python: {'Priya'}
Students in only one course: {'Priya', 'Kiran'}

Here you can see the set over all concepts:

Reference:
(https://www.w3schools.com/python/python_sets.asp)
(https://pythongeeks.org/sets-in-python/)
(https://www.geeksforgeeks.org/python/sets-in-python/)

Top comments (0)