InterviewSolution
| 1. |
What is the difference between set and frozenset? |
|
Answer» Set is a collection data type in Python. It is a collection of unique and immutable objects, not necessarily of same types. A set object can be created by a literal representation as well as using built-in set() function. Comma separated collection of items enclosed in curly brackets is a set object. >>> s={10,'Hello', 2.52} >>> type(s) <class 'set'>You can also USE built-in set() function which in fact is constructor of set class. It constructs a set object from an iterable argument such as list, tuple or STRING. >>> s1=set([10,20,30]) >>> s1 {10, 20, 30} >>> s2=set((100,200,300)) >>> s2 {200, 100, 300} >>> S3=set('Hello') >>> s3 {'o', 'e', 'l', 'H'}Items in the iterable argument may not appear in the same order in set collection. Also, set is a collection of unique objects. THEREFORE, even if the iterable contains repeated occurrence of an item, it will appear only one in set. You can see just one presence of ‘l’ even if it appears twice in the string. Items in the set collection must be mutable. It means a list or a dict object cannot be one of the items in a set although tuple is allowed. >>> s={1,(2,3)} >>> s {1, (2, 3)} >>> s={1,[2,3]} Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> s={1,[2,3]} TypeError: unhashable type: 'list'Even though set can contain only immutable objects such as number, string or tuple, set itself is mutable. It is possible to perform add/remove/clear operations on set. >>> s1=set([10,20,30]) >>> s1.add(40) >>> s1 {40, 10, 20, 30} >>> s1.remove(10) >>> s1 {40, 20, 30}Frozenset object on the other hand is immutable. All other characteristics of frozenset are similar to normal set. Because it is immutable add/remove operations are not possible. >>> f=frozenset([10,20,30]) >>> f frozenset({10, 20, 30}) >>> f.add(40) Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> f.add(40) AttributeError: 'frozenset' object has no attribute 'add'Python’s set data type is implementation of set as in set theory of Mathemetics. Operations such as union, intersection, difference etc. can be done on set as well as frozenset. |
|