Codied To Clipboard !
Home > Notes > python
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)
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)
using add() , we can add the item to the list.
test = {"abc","def","ghi"}
test.add("ijk")
print(test)
using remove method we can delete the elemebts from set.
test = {"abc","def","ghi"}
test.remove("abc")
print(test)
Using For loop we can loop the items one by one.
test = {"abc","def","ghi"}
for i in test:
print(I)
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)
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)
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)
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)
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)
Returns a copy of the set
test = {1,2,3,4,5}
res1 = test.copy()
print(res1)