#PYTHON(DAY9)
Sets and it’s methods
sets
- sets are a cluster of data values, they are not ordered
- we declare sets by using ‘{ }’
- sets do not have duplicate values
- we can use set class to perform task
- sets have methods that are unique to sets, like union, intersection etc
- to create an empty set, use set(). using {} gives an empty dictionary
x = {1,2,3,4, print, 'three'}
print(x, len(x), type(x), sep ='\n')
And the expected output is:
{1, 2, 3, 4, <built-in function print>, 'three'}
6
<class 'set'>
creating set with one element:
x = {8}
print(x)
And the expected output is:
{8}
Note: As, in tuples there is no need to place “ , “, for creating set with one element
Sets can not have duplicate elements
a = 'malayalam'
x = set(a)
print(x, len(x), type(x), sep = '\n')
And the expetced output is:
{'l', 'm', 'a', 'y'}
4
<class 'set'>
sets have no order in python
x = set()
print(x)
And the expected output is:
set()
Methods in set
Python has a set of built-in methods that you can use on sets
print(dir(set))
And the list methods are:
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
Now, let’s talk about some of the important methods in set
add()
- it adds exactly one element to the set
x = {1,2,3,4}
x.add(6)
print(x)
output is:
{1, 2, 3, 4, 6}
x.add(5)
print(x)
output is:
{1, 2, 3, 4, 5, 6}
add() takes exactly one element only
pop()
- it is going to pop a random element, pop in sets takes no input/arg
print(x)
a = x.pop()
print(x,a, sep ='\n')
output is:
{1, 2, 3, 5}
{2, 3, 5}
1
copy()
a = set('hellow world!')
b = a
print(a,b, sep = '\n')
print()
a.update(['xx','yy'])
print(a,b, sep = '\n')
print()
output is:
{'!', 'h', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'yy', 'xx', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'yy', 'xx', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
a = set('hellow world!')
b = a.copy()
print(a,b, sep = '\n')
print()
a.update(['xx','yy'])
print(a,b, sep = '\n')
print()
output is:
{'!', 'h', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'yy', 'xx', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
{'!', 'h', 'o', 'w', ' ', 'd', 'l', 'e', 'r'}
clear()
- clear() is used to clear the set
print(b)
b.clear()
print(b)
output is:
set()
set()
No comments:
Post a Comment