Sets
Sets
By Kaloyan Totev
Defining a set – set(<iter>)
• x = set(['foo', 'bar', 'baz', 'foo', 'qux'])
• {'qux', 'foo', 'bar', 'baz'}
• >>> set('foo')
What is the difference ?
• >>> {'foo'}
• {'foo'}
• >>> set('foo')
• {'o', 'f'}
There is only one way to define
empty set
• >>> x = set()
• >>> type(x)
• <class 'set'>
• >>> x = {}
• >>> type(x)
• <class 'dict'>
The elements in a set can be objects
of different types:
• >>> x = {42, 'foo', 3.14159, None}
• {None, 'foo', 42, 3.14159}
Elements must be immutable
• x = {42, 'foo', (1, 2, 3), 3.14159}
{42, 'foo', 3.14159, (1, 2, 3)}
• >>> a = [1, 2, 3]
• >>> {a}
• Traceback (most recent call last):
• File "<pyshell#70>", line 1, in <module>
• {a}
• TypeError: unhashable type: 'list'
Length and membership
• >>> x = {'foo', 'bar', 'baz'}
• >>> len(x)
•3
• >>> 'bar' in x
• True
Set operations
Union Operation
• >>> x1 = {'foo', 'bar', 'baz'}
• >>> x2 = {'baz', 'qux', 'quux'}
• >>> x1 | x2
• {'baz', 'quux', 'qux', 'bar', 'foo’}
• Pop()
• Clear()
Frozen sets
• >>> x = frozenset(['foo', • Python provides another
'bar', 'baz']) built-in type called a
frozenset, which is in all
• >>> x
respects exactly like a set,
• frozenset({'foo', 'baz', except that a frozenset is
'bar'}) immutable. You can perform
non-modifying operations on
a frozenset
Iterating through a set
• for element in my_set:
• print(element)
Membership
• if 3 in my_set:
print("3 is in the set")
• Sets are commonly used in Python for tasks that involve
handling collections of unique
• elements, such as removing duplicates from a list or
performing set-based mathematical
• Operations
exercises
• Write a Python program to remove an item from a set if it is
present in the set.
• Write a Python program to check if two given sets have no
elements in common.
• Write a Python program to remove all duplicates from a given list
of strings and return a list of unique strings. Use the Python set
data type.
exercises
• Write a Python program to find the third largest number from a
given list of numbers.Use the Python set data type.
• Given two sets of numbers, write a Python program to find the
missing numbers in the second set as compared to the first and
vice versa. Use the Python set.