January 6, 2020

Sets in Python

Sets in Python

Sets are collection of unique objects.
Sets contain values of any immutable data type.
Denoted with curly braces, { and }, in Python.

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

set function will be used to convert any other data type to Python set.
nums = set([1,1,2,3,3,3,4]) # duplicates will be removed
>>> a = set('abracadabra')
new_set=set(student_list)
s1 = set(input().split())
set([]) # an empty set
empty_set = set()

>>> print set('Python Blog')

>>> print set({'Python' : 'Satya', 'Rank' : 66})

intersection function to get common elements in two sets.
new_set.intersection(old_set)
set(user1).intersection(user3)
>>> a & b # letters in both a and b

union function to get all unique elements in two sets.
new_set.union(old_set)
>>> a | b # letters in a or b or both
print s.union({"Blog":1})

difference function to get elements which are in first set and not in second set. new_set.difference(old_set)
set(user2).difference(user6)
>>> a - b # letters in a but not in b
>>> a ^ b # letters in a or b but not both
print(*sorted(list(M.symmetric_difference(N))), sep='\n')

issubset function is to check whether one set is subset of another set or not. aset.issubset(otherset)
{6,90}.issubset(yourSet)

add function to add new elements to Python set.
mySet.add("house")
set3.add((6, 2))
for _ in range(int(input())): s.add(input())

remove, discard, pop functions are used to remove elements from sets in Python.
mySet.remove(6.2)
>>> myset.discard(99)
mySet.pop()
mySet.clear()

pySet.update([8, 2, 9, 4]) # update() only works for iterable objects
set8.update({1, 6}, [5, 13])

print(len(nums))
type(new_set)
>>> 'grass' in basket
>>> a = {x for x in 'abracadabra' if x not in 'abc'}


Related 
Python Articles:  Tuples in Python           Lists in Python

No comments:

Post a Comment