0% found this document useful (0 votes)
30 views13 pages

Sets - Jupyter Notebook

The document discusses sets in Python. It defines what a set is, demonstrates how to perform common set operations like union, intersection, difference and symmetric difference, and shows how to add/remove elements from a set. It also discusses frozen sets and set comprehensions.

Uploaded by

anyone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views13 pages

Sets - Jupyter Notebook

The document discusses sets in Python. It defines what a set is, demonstrates how to perform common set operations like union, intersection, difference and symmetric difference, and shows how to add/remove elements from a set. It also discusses frozen sets and set comprehensions.

Uploaded by

anyone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Sets

A set object is an unordered collection of distinct hashable objects. Common


uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference

In [12]:

set_1={1,4,2,3,"hello",'vardhaman',2.48}
s3={'college','of','engineering','apple'}
print(type(set_1))

<class 'set'>

In [13]:

set2={1,1.24,'hello',(5,6,7,'list'),("in",'tuple','inside','set'),'last'}
print(set2)
set2.add('another')
set2.discard((5,6,7,'list'))
set2.remove(("in",'tuple','inside','set'))
print(set2.pop())
set2.update(set_1)
print(set2)

{1, 1.24, ('in', 'tuple', 'inside', 'set'), (5, 6, 7, 'list'), 'last', 'hell
o'}

{1.24, 1, 2, 3, 4, 'last', 'vardhaman', 2.48, 'another', 'hello'}

In [14]:

print(set_1)
print(s3)

{1, 2, 3, 4, 'vardhaman', 2.48, 'hello'}

{'apple', 'college', 'engineering', 'of'}

In [15]:

set_1=set((1,2.3,8,5,4,7))
set_2={1,28,4,"hello","students",2.4}
print(type(set_1))
print(type(set_2))
print(set_1)
print(set_2)

<class 'set'>

<class 'set'>

{1, 2.3, 4, 5, 7, 8}

{1, 2.4, 4, 'students', 'hello', 28}

In [16]:

set1 = {"apple", "banana", "cherry",'kiwi',"apple","orange","mango"}

In [17]:

print(set1)

{'apple', 'orange', 'mango', 'banana', 'cherry', 'kiwi'}

In [18]:

set2={100,254,90,47,200,478,100,254,47,94,78}
print(set2)

{100, 200, 78, 47, 254, 94, 90, 478}

In [19]:

set2={100,254,90,47,200,478}
print(set2)

{100, 478, 200, 90, 254, 47}

In [20]:

print(set2)

{100, 478, 200, 90, 254, 47}

In [21]:

Days={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}

In [22]:

print(Days)

{'Saturday', 'Thursday', 'Tuesday', 'Sunday', 'Friday', 'Monday', 'Wednesda


y'}

In [23]:

for i in Days:
print(i)

Saturday

Thursday

Tuesday

Sunday

Friday

Monday

Wednesday

In [24]:

print(set1)

{'apple', 'orange', 'mango', 'banana', 'cherry', 'kiwi'}

In [25]:

basket = set(('apple', 'orange', 'apple', 'pear', 'orange', 'banana'))


print(basket)

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

In [26]:

ls2=[1,2,4,5,2,6,8,1,9,4]
print(set(ls2))

{1, 2, 4, 5, 6, 8, 9}

In [27]:

if 'mango' in basket:
print('yes')
else:
print('no')

no

Set Functions

In [28]:

print(help(set))

Help on class set in module builtins:

class set(object)

| set() -> new empty set object

| set(iterable) -> new set object

| Build an unordered collection of unique elements.

| Methods defined here:

| __and__(self, value, /)

| Return self&value.

| __contains__(...)

| x.__contains__(y) <==> y in x.

| __eq__(self, value, /)

| Return self==value.

| ge (self value /)
In [29]:

st1={2,8,6,10,45,2,89,6}
print(st1)

{2, 6, 8, 89, 10, 45}

In [30]:

st1.add(47) # adds the specified item into set


print(st1)

{2, 6, 8, 89, 10, 45, 47}

In [31]:

st1.add(12)
print(st1)

{2, 6, 8, 89, 10, 12, 45, 47}

In [32]:

st1.remove(2)
print(st1)

{6, 8, 89, 10, 12, 45, 47}

In [34]:

st1.remove(20) # Remove the specified item


print(st1)

---------------------------------------------------------------------------

KeyError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_18352/884427205.py in <module>

----> 1 st1.remove(20) # Remove the specified item

2 print(st1)

KeyError: 20

In [35]:

st1.discard(12) # Remove the specified item without error


print(st1)

{6, 8, 89, 10, 45, 47}

In [36]:

# Remove any arbitary item from set


print(st1.pop())
print(st1)

{8, 89, 10, 45, 47}

In [37]:

st3={'hello','iam','from','vardhaman','college'}
print(st3)

{'college', 'vardhaman', 'hello', 'iam', 'from'}

In [38]:

print(st3.pop())

college

In [39]:

# Merging two sets with update without duplicates


st2={"hello",'randam','strings'}
st3={45,87.98,77,45}
st1.update(st3)
st1.add('hello')
st1.add('randam')
st1.add('string')
print(st1)

print(st1.clear())

{8, 10, 'string', 45, 77, 47, 'randam', 'hello', 87.98, 89}

None

In [41]:

new_set=st1.copy()
print(st1)
print(new_set)
st1.add(49)
print(st1)
print(new_set)

set()

set()

{49}

set()

In [42]:

del new_set

1. Union of two Sets (| Operator)

2. Intersection of two sets (& Operator)

3. Difference between the two sets (- Operator)

4. Symmetric Difference of two sets (^ Operator)

5. isdisjoint

6. issubset

7. issuperset
In [48]:

set1={3,6,2,1,0,0,6,7}
set2={4,5,6,7,0}

print(set1.symmetric_difference_update(set1.union(set2)))
print(set1)

None

{4, 5}

In [49]:

real = set((0,1,2,3,4,5,6,7,8,9))
odd = set((1,3,5,7,9))
even = set((2,4,6,8))
random=set((5,9,3,7,2))
print(real,odd,even,random)

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} {1, 3, 5, 7, 9} {8, 2, 4, 6} {2, 3, 5, 7, 9}

In [50]:

# letters in both first or second sets


print(even | random)

# Return a set containing the union of sets


print(odd.union(random))
print(odd.update(random))

{2, 3, 4, 5, 6, 7, 8, 9}

{1, 2, 3, 5, 7, 9}

None

In [51]:

odd

Out[51]:

{1, 2, 3, 5, 7, 9}
In [52]:

set2.difference_update(set1)
set2

Out[52]:

{0, 6, 7}

In [53]:

set1={3,6,2,1,0,0,6,7}
set2={4,5,6,7,0}
# letters in first but not in second sets
print(set2 - set1 )
# Returns a set containing the difference between two sets
print(set1.difference_update(set2))

{4, 5}

None

In [54]:

set1

Out[54]:

{1, 2, 3}

In [55]:

8 in st1

Out[55]:

False
In [56]:

# letters comman in both first and second sets


print(odd & even)

# Returns a set, that is the intersection of two or more sets


print(random.intersection_update(even))

{2}

None

In [57]:

help(set1.isdisjoint)

Help on built-in function isdisjoint:

isdisjoint(...) method of builtins.set instance

Return True if two sets have a null intersection.

In [58]:

set2

Out[58]:

{0, 4, 5, 6, 7}

In [59]:

# letters in first or second but not both


print(even ^ random )

print(set2.symmetric_difference_update(set1))

{8, 4, 6}

None

In [60]:

set2

Out[60]:

{0, 1, 2, 3, 4, 5, 6, 7}

Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the
sets by using which we can check whether a set is a subset, superset, or equivale
nt to other set.

In [61]:

st1={1,0,2}
st2={2,0,1}
st2.issubset(st1)

Out[61]:

True

In [62]:

odd.isdisjoint(even)

Out[62]:

False

Set Comprehension
In [63]:

a = {x for x in range(0,50) if x%2!=0 }


print(a)

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39,
41, 43, 45, 47, 49}

In [64]:

ls=[x for x in range(0,20) if x%5!=0 ]


print(ls)

[1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19]

In [65]:

new = set("alacazam")
print(new)

{'a', 'z', 'l', 'm', 'c'}

Python frozenset()
The frozenset() function returns an immutable frozenset object initialized with el
ements from the given iterable. While elements of a set can be modified at any tim
e, elements of the frozen set remain the same after creation.

In [69]:

normal_set = set(["a", "b","c"])

print("Normal Set")
print(normal_set)

# A frozen set
st3 = frozenset(["e", "f", "g",'a'])

print("\nFrozen Set")
print(st3)

Normal Set

{'c', 'b', 'a'}

Frozen Set

frozenset({'g', 'f', 'e', 'a'})

In [67]:

st3.difference(st1)

Out[67]:

frozenset({'a', 'e', 'f', 'g'})


In [71]:

print(frozenset.union(normal_set))

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_18352/1430241181.py in <module>

----> 1 print(frozenset.union(normal_set))

TypeError: descriptor 'union' for 'frozenset' objects doesn't apply to a 'se


t' object

In [72]:

# to create a simple Hash Function with ASCII values


def Hash(key):
h=0
for char in key:
h+=ord(char)
return h%3
Hash('100')

Out[72]:

In [73]:

print(Hash('apple'),Hash('banana'),Hash('cherry'),Hash('kiwi'),Hash('orange'),Hash('mango')

2 0 2 1 0 2

In [74]:

# Program to demonstrate various operations on sets.


s = {1,2,3,4,6,9}
t = {4,5,6,1,3,3}
u = {1,2,3,4}

print(f"Set S = {s} T = {t} U = {u}")


print(f"length of sets S = {len(s)} T = {len(t)} U = {len(u)}")
print(f"Minimum of sets S = {min(s)} T = {min(t)} U = {min(u)}")
print(f"Maximum of sets S = {max(s)} T = {max(t)} U = {max(u)}")
print(f"Sum of sets S = {sum(s)} T = {sum(t)} U = {sum(u)}")
print(f"Sets after sorting S = {sorted(s)} T = {sorted(t)} U = {sorted(u)}")

s.add(5)
print('Updated set after add:', s)
s.discard(5)
print('Updated set_after discard:', s)
s.remove(1)
print('Updated set after remove:', s)

print('\nPopped element', s.pop())


print('Updated set after pop:', s)

print(f"Union of set {s} and {t}: ",s.union(t)) #s|t


print(f"Difference of set {s} and {u}: ",s.difference(u)) #s-u
print(f"Intersection of set {s} and {u}: ",s.intersection(u)), #s&u
print(f"Symmetric Difference of set {s} and {u}: ",s.symmetric_difference(u)) #s^u

s.difference_update(u)
print(f"Difference of set {s} and {u}: ",s)

t.intersection_update(u)
print(f"Intersection of set {t} and {u}: ",t)

u.symmetric_difference_update(s)
print(f"Symmetric Difference of set {u} and {s}: ",u)

print(f"issubset of set {u} and {s}: ",u.issubset(s))


print(f"isdisjoint of set {u} and {s}: ",u.isdisjoint(s))
print(f"issuperset of set {u} and {s}: ",u.issuperset(s))

s.clear()
print('Updated set after clear:', s)

Set S = {1, 2, 3, 4, 6, 9} T = {1, 3, 4, 5, 6} U = {1, 2, 3, 4}

length of sets S = 6 T = 5 U = 4

Minimum of sets S = 1 T = 1 U = 1

Maximum of sets S = 9 T = 6 U = 4

Sum of sets S = 25 T = 19 U = 10

Sets after sorting S = [1, 2, 3, 4, 6, 9] T = [1, 3, 4, 5, 6] U = [1, 2,


3, 4]

Updated set after add: {1, 2, 3, 4, 5, 6, 9}

Updated set_after discard: {1, 2, 3, 4, 6, 9}

Updated set after remove: {2, 3, 4, 6, 9}

Popped element 2

Updated set after pop: {3, 4, 6, 9}

Union of set {3, 4, 6, 9} and {1, 3, 4, 5, 6}: {1, 3, 4, 5, 6, 9}

Difference of set {3, 4, 6, 9} and {1, 2, 3, 4}: {9, 6}

Intersection of set {3, 4, 6, 9} and {1, 2, 3, 4}: {3, 4}

Symmetric Difference of set {3, 4, 6, 9} and {1, 2, 3, 4}: {1, 2, 6, 9}

Difference of set {6, 9} and {1, 2, 3, 4}: {6, 9}

Intersection of set {1, 3, 4} and {1, 2, 3, 4}: {1, 3, 4}

Symmetric Difference of set {1, 2, 3, 4, 6, 9} and {6, 9}: {1, 2, 3, 4,


6, 9}

issubset of set {1, 2, 3, 4, 6, 9} and {6, 9}: False

isdisjoint of set {1, 2, 3, 4, 6, 9} and {6, 9}: False

issuperset of set {1, 2, 3, 4, 6, 9} and {6, 9}: True

Updated set after clear: set()

Excersices

1: Add a list of elements to a set

2: Return a new set of identical items from two sets

3: Get Only unique items from two sets

4: Update the first set with items that don’t exist in the first set
5: Remove items from the set at once

6: Return a set of elements present in Set A or B, but not both

7: Check if two sets have any elements in common. If yes, display the common eleme
nts

8: Update set1 by adding items from set2, except common items

9: Remove items from set1 that are not common to both set1 and set2

In [ ]:

You might also like