Sets
Sets are used to store multiple items in a single variable
Sets are defined with {}.
Set is one of 4 built-in data types in Python used to store collections of data.
A set is a collection which is unordered, unchangeable*, and unindexed.
Does not allow duplicate elements
set = {} will return data type as dictionary. SO we have to use set() method
to return <class: set>
Set Operations are explained in the following example code:
s1 = {}
print(type(s1))
#<class 'dict'>
s2 =set()
print(type(s2))
#<class 'set'>
s3 = set(("apple", "banana", "cherry")) # note the double round-brackets
print(s3) #{'banana', 'apple', 'cherry'}
aset ={1,2,3,4,5,5}
print(aset)
#{1, 2, 3, 4, 5}
aset =set("Hello")
print(aset)
#{'H', 'e', 'o', 'l'} -->order immaterial, only one l is printed
aset = set()
aset.add(11)
aset.add(22)
aset.add(33)
#aset.discard()
print(aset) #{33,11,22}
aset.pop()
print(aset) #{11,22}
#set Operations
odd = {1, 3, 5, 7, 9}
even = {0, 2, 4, 6, 8, 10}
primes = {3, 5, 7}
print(odd.union(even)) #{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(odd.intersection(primes)) #{3, 5, 7}
print(even.intersection(primes)) #set()
print(odd.difference(primes)) #{1, 9}
print(odd.symmetric_difference(primes)) #{1, 9}
print(odd.symmetric_difference(even)) #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a = {1,2,3,4,5,6,7,8,9}
b = {1,2,3,10,11,12}
a.update(b)
print(a) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
a.intersection_update(b)
print(a) #{1, 2, 3, 10, 11, 12}
a.add(13)
print(a) # {1, 2, 3, 10, 11, 12, 13}
print(b) #{1, 2, 3, 10, 11, 12}
b.pop()
print(b) #{2, 3, 10, 11, 12}
def odd_even():
n = int(input('EnterNumper < 10 Please')) #5
if n in odd:
print('Odd number')
elif n in even:
print('Even number')
# odd_even() # Odd Number
print(a.issuperset(b)) # True
print(a.isdisjoint(b)) # False
c ={7,8,9}
print(a.isdisjoint(c)) # True
d = c # copy the reference be careful when u change the original alsowill change
print(c,d) #{8, 9, 7} {8, 9, 7}
d.add(18)
print(c,d) # {8, 9, 18, 7} {8, 9, 18, 7} dangerous original also changed
c ={7,8,9}
d = c.copy()
d.add(18)
print(c,d) # {8, 9, 7} {8, 9, 18, 7}
The results are given in the same line as comments for easy reference and understanding.
Happy set learning with AMETODL😈😈😈
No comments:
Post a Comment