sets in python

By | March 5, 2019

Sets in Python-: A set in Python is an unordered collection of objects used when membership and uniqueness in the set are main things we need to know about that object. Like dictionary keys  the items in a set must be immutable and hash-able. This means that  floats, strings, and tuples can be members of a set, but lists, dictionaries, and sets themselves can not.

Set operations-: In addition to the operations that apply to collections in general such as in  len, and iteration in for loops, sets have several set-specific operations as like

>>> x = set([1, 2, 3, 1, 3, 5])     1
>>> x
{1, 2, 3, 5}                        2
>>> x.add(6)                        3
>>> x
{1, 2, 3, 5, 6}
>>> x.remove(5)                     4
>>> x
{1, 2, 3, 6}
>>> 1 in x                          5
True
>>> 4 in x                          5
False
>>> y = set([1, 7, 8, 9])
>>> x | y                           6
{1, 2, 3, 6, 7, 8, 9}
>>> x & y                           7
{1}
>>> x ^ y                           8
{2, 3, 6, 7, 8, 9}
>>>

We can create a set by using set on a sequence, such as a list 1. When a sequence is made into a set, duplicates are removed 2. After creating a set by using the set function we can use add 3 and remove 4 to change the elements in the set. The in keyword is used to check for membership of an object in a set 5. we can also use | 6 to get the union, or combination, of two sets and to get their intersection 7, and  8 to find their symmetric difference that is elements that are in one set or the other but not both.

These examples are not a complete listing of set operations but are enough to give us a good idea of how sets work.

Frozensets -:We know that the sets aren’t immutable and hashable  they can not belong to other sets. To remedy that situation Python has another set type this is called the frozenset which is just like a set but can not be changed after creation. Because frozensets are immutable and hashable  they can be members of other sets.

>>> x = set([1, 2, 3, 1, 3, 5])
>>> z = frozenset(x)
>>> z
frozenset({1, 2, 3, 5})
>>> z.add(6)
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    z.add(6)
AttributeError: 'frozenset' object has no attribute 'add'
>>> x.add(z)
>>> x
{1, 2, 3, 5, frozenset({1, 2, 3, 5})}

 

Creating a set in Python-: The set can be created by enclosing the comma separated items with the curly braces. Python also provides the set method which are used to create the set by the passed sequence. example of set method

Days = set(["Monday", "Tuesday", "Wednesday"])  
print(Days)  
print(type(Days))  
print("looping through the set elements ... ")  
for i in Days:  
    print(i)

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *