Sitemap
Vcanhelpsu

Vcanhelpsu

Python Sets

2 min readDec 1, 2024

Python Sets

Sets in Python programming are an unordered storage collection of unique elements. Set data types declared in Python programs can be modified at any time, which means you can add new set elements or remove old set elements from previously declared set data type elements. Additionally, you can perform tasks like testing membership in set elements, removing duplicate elements in an existing set sequence, and unioning set elements, intersecting unique set elements, as well as applying set mathematical operations like difference and symmetric difference.

Press enter or click to view image in full size

Creating a New Set in Python.

Python programmers can create a set element in a program using left and right curly braces {} with comma-operator separated set element values ​​or using the set() constructor with a repetition (such as a list or tuple).

# Declaring a set using curly braces in Python program

test_set = {7, 9, 1, 5, 8, 3, 0 }

# Creating a new set using set() constructor in Python

sample_set = set([4, 7, 3, 9, 10, 1])

Basic operations on sets in Python programs.

Adding elements to a set — The add() method is used to add a new element to a set in a Python program, and the update() Python method is used to add multiple set elements (any other repetition) at once.

test_set.add(2)

print(test_set) # the result is — {7, 9, 1, 5, 8, 3, 0 }

sample_set.update([11, 12, 15])

Get Vcanhelpsu’s stories in your inbox

Join Medium for free to get updates from this writer.

print(test_set) # the result is — {7, 9, 1, 5, 8, 3, 0, 11, 12, 15 }

Deleting Set Elements in Python — In Python programming, Python methods like remove(), discard(), or pop() are used to remove elements from a set.

test_set.remove(0)

print(my_set) # the result is — {7, 9, 1, 5, 8, 3, 0 }

test_set.discard(15)

print(test_set) # the result is — {7, 9, 1, 5, 8, 3, 11, 12}

popped_element = test_set.pop()

print(test_set) # the result is — { 9, 1, 5, 8, 3, 11, 12}

print(popped_element) # the result is — { 9, 1, 5, 8, 3, 11, 12} (randomnly remove set pop element 7)

Operations on Python Sets — Apply set operations like set union (|), intersection (&), difference (-), and symmetric difference (^) in Python programs We can do it.

setgroup1 = {10, 9, 8, 7, 6}

setgroup2 = {5, 4, 3, 2, 1}

# let print two different set union element

print(setgroup1 | setgroup2) # the result is — {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

# Python set intersection setgroup1 = {10, 9, 8, 7, 6,5} 2 = {5, 4, 3, 2, 1,10}

Continue Reading On — https://vcanhelpsu.com

--

--