43.Set-Built-in Functions and Methods, frozen set

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.
Function         Description
all()                 Returns True if all elements of the set are true (or if the set is empty).
any()               Returns True if any element of the set is true. If the set is empty, returns False.
enumerate()    Returns an enumerate object. It contains the index and value for all the items of the set 
                        as a pair.
len()                Returns the length (the number of items) in the set.
max()              Returns the largest item in the set.
min()               Returns the smallest item in the set.
sorted()           Returns a new sorted list from elements in the set(does not sort the set itself).
sum()              Returns the sum of all elements in the set.

Example:
>>> S={1,0,2,3}
>>> all(S)
False
>>> any(S)
True
>>> for i in enumerate(S):
print(i)
(0, 0)
(1, 1)
(2, 2)
(3, 3)
>>> len(S)
4
>>> max(S)
3
>>> min(S)
0
>>> SS=sorted(S)
>>> SS
[0, 1, 2, 3]
>>> sum(S)
6

Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the  methods that are available with the set objects:

Method                      Description
add()                          Adds an element to the set
clear()                        Removes all elements from the set
copy()                        Returns a copy of the set
difference()                Returns the difference of two or more sets as a new set
difference_update()    Removes all elements of another set from this set
discard()                     Removes an element from the set if it is a member. 
                                   (Do nothing if the element is not in set)
intersection()              Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint()                  Returns True if two sets have a null intersection
issubset()                    Returns True if another set contains this set
issuperset()                 Returns True if this set contains another set
pop()                           Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove()                     Removes an element from the set. If the element is not a member, raises a 
                                    KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
union()                       Returns the union of sets in a new set
update()                     Updates the set with the union of itself and others

Examples
>>> A={3,2,1,4}
>>> A.add(5)
>>> A
{1, 2, 3, 4, 5}
>>> B=A.copy()
>>> B
{1, 2, 3, 4, 5}
>>> B.clear()
>>> B
set()
>>> A
{1, 2, 3, 4, 5}
>>> A.discard(5)
>>> A
{1, 2, 3, 4}
>>> A.update({5,6})
>>> A
{1, 2, 3, 4, 5, 6}
>>> B={1,2}
>>> B.issubset(A)
True
>>> A.union(B)
{1, 2, 3, 4, 5, 6}
>>> A.intersection(B)
{1, 2}
>>> A.difference(B)
{3, 4, 5, 6}

Set Membership Test
We can test if an item exists in a set or not, using the in keyword.

>>>my_set = set("apple") 
>>>print('a' in my_set)
True  
>>>print('p' not in my_set)
False 

Iterating Through a Set

We can iterate through each item in a set using a for loop.
>>> s={3,2,1,5}
>>> for i in s:
print(i)
1
2
3
5

Python Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the frozenset() function.

This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that add or remove elements.

>>> a=frozenset([1,2,3,4])
>>> b=frozenset([3,4,5,6])
>>> a|b
frozenset({1, 2, 3, 4, 5, 6})
>>> a-b
frozenset({1, 2})
>>> a&b
frozenset({3, 4})
>>> a.issubset(b)
False
>>> c={2,3}
>>> c.issubset(a)
True
>>> a.add(9)
Traceback (most recent call last):
  File "<pyshell#102>", line 1, in <module>
    a.add(9)
AttributeError: 'frozenset' object has no attribute 'add'
>>> a.remove(2)
Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
    a.remove(2)
AttributeError: 'frozenset' object has no attribute 'remove'

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators