Home > Notes > python

Python Set

python

Python Variable
Python Conditional statement
Python loops
Python List
Python Tuple
Python String
Python Set
Python Dictionary
Python Functions
Python Exceptions
Python File Operation
Python Map
Python Lambda
Python Filter
Python OOPS

Python Set

Set Overview

Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable*, and unindexed. Set items are unchangeable, but you can remove items and add new items. Sets are written with curly brackets.

test = {1,2,3,4,5}
print(test)

Access Items

You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword

test = {"Cricket","Carm","FootBall"}
for i in test:
 print(I)
print("banana" in tset)

Add item to set

using add() , we can add the item to the list.

test = {"abc","def","ghi"}
test.add("ijk")
print(test)

Removing item to set

using remove method we can delete the elemebts from set.

test = {"abc","def","ghi"}
test.remove("abc")
print(test)

Set Loop items

Using For loop we can loop the items one by one.

test = {"abc","def","ghi"}
for i in test:
 print(I)

Set union

it will combine the set and create a new set

set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.union(set2)
print(res1)

Set intersection

it will get the common value from sets.

set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res2 = set1.intersection(set2)
print(res2)

Set difference

Returns a set containing the difference between two or more sets

set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res2 = set1.difference(set2)
print(res2)

Set symmetric_difference()

Returns a set with the symmetric differences of two sets

set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res2 = set1.symmetric_difference(set2)
print(res2)

Set issubset()

Return True if all items in set a are present in set b:

set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.issubset(b)
print(res1)

Set copy()

Returns a copy of the set

test = {1,2,3,4,5}
res1 = test.copy()
print(res1)