Set
A set is an unordered collection of items.
Every element is unique (no duplicates).
The set itself is mutable. We can add or remove items from it. Does not support indexing. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
•Any immutable data type can be an element of a set: a number, a string, a tuple. Mutable (changeable) data types cannot be elements of the set. The elements in the set cannot be duplicates.
•The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
•There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.
•A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
•thisset = {“apple”, “banana”, “cherry”}
print(thisset)
•Access Items
•You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
•But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
thisset = {“apple”, “banana”, “cherry”}
for x in thisset:
print(x)
Example: thisset = {“apple”, “banana”, “cherry”}
print(“banana” in thisset)
•Once a set is created, you cannot change its items, but you can add new items.
•Add Items
1. To add one item to a set use the add() method.
2. To add more than one item to a set use
the update() method.
Programs
1. thisset = {“apple”, “banana”, “cherry”}
thisset.add(“orange”)
print(thisset)
2.thisset = {“apple”, “banana”, “cherry”}
thisset.update([“orange”, “mango”, “grapes”])
print(thisset)
3.print(sorted(thisset))
Set Operation
a={2,3,4,5,12}
b={3,4,7,8,2,5}
c=a|b #union
print(c)
c=a&b #intersection
print(c)
c=b-a #diffence
print(c)
c=a-b
print(c)
c=a<=b # b is supperset
print(c)
The set() Constructor
•It is also possible to use the set() constructor to make a set.
•Using the set() constructor to make a set:”””
•#Same as {“a”, “b”,”c”}
•normal_set = set([“a”, “b”,”c”])
•# Adding an element to normal set is fine
•normal_set.add(“d”)
•print(“Normal Set”)
•print(normal_set)
#3 using constructor
•thisset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets
•print(thisset)
•#why set in python
Set Operation Contd..
Advantages of Python Sets
1. Sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently
3. Remove duplicate values from a list or tuple and to perform common
4. To perform math operations like unions and intersections. ..
•Int Immutable float Immutable
•Bool Immutable tuple Immutable
•Str Immutable frozeset Immutable
•set Mutable(changeable) list Mutable
•dictionary Mutable
Set Operation Contd..
•thisset = {“apple”, “banana”, “cherry“}
•Remove “banana” by using remove() method:
•thisset = {“apple”, “banana”, “cherry”}
thisset.remove(“banana”)
print(thisset)
print(len(thisset))
•POP-You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.
•The return value of the pop() method is the removed item.
Example
•thisset = {“apple”, “banana”, “cherry”}
x = thisset.pop()
print(x)
print(thisset)
•Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
•The clear() method empties the set:
• thisset = {“apple”, “banana”, “cherry”}
thisset.clear()
print(thisset)
•The del keyword will delete the set completely:
thisset = {“apple”, “banana”, “cherry”}
del thisset
print(thisset)
Set Operation Contd..
This is how you perform the well-known operations on sets in Python:
A | B A.union(B) | Returns a set which is the union of sets A and B. |
A |= B A.update(B) | Adds all elements of array B to the set A. |
A & B A.intersection(B) | Returns a set which is the intersection of sets A and B. |
A – B A.difference(B) | Returns the set difference of A and B (the elements included in A, but not included in B). |
A ^= B A.symmetric_difference_update(B) | Writes in A the symmetric difference of sets A and B. |
A <= B A.issubset(B) | Returns true if A is a subset of B. |
A >= B A.issuperset(B) | Returns true if B is a subset of A. |
A < B | Equivalent to A <= B and A != B |
A > B | Equivalent to A >= B and A != B |
Set operation(union , intersection etc)
•a={2,3,4,5}
•b={3,4,7,8,2,5}
•c=a|b #union
•print(c)
•c=a&b #intersection
•print(c)
•c=a-b #diffence
•print(c)
•c=a<=b# b is supperset
•print(c)
Dictionary
•Dictionary is an unordered collection of data values.
•A Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’.
•A dictionary has a key: value pair. Each key-value pair is separated by a colon :, whereas each key is separated by a ‘comma’.
•Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
• Dictionary can also be created by the built-in function dict().
Example
dy= {} # empty dictionary
dy= {1: ‘apple’, 2: ‘ball’} # dictionary with integer keys
dy= {‘name’: ‘John’, 1: [2, 4, 3]} #dictionary with mixed keys
dy= dict({1:’apple’, 2:’ball’}) # using dict()
dy= dict([(1,’apple’), (2,’ball’)]) # from sequence having each item as
a pair
Accessing elements from a dictionary
•Key can be used either inside square brackets or with the get() method. (The difference while using get() is that it returns None instead of KeyError, if the key is not found.)
Accessing elements from a dictionary
•Key can be used either inside square brackets or with the get() method. (The difference while using get() is that it returns None instead of KeyError, if the key is not found.)
Change or add elements in a dictionary
Delete or Remove Elements
Example
dt = {‘name’:’Ram’, ‘age’: 26}
print(‘the existing dictionary is:’,dt)
dt[‘age’] = 27
print(dt)
dt[‘address’] = ‘Gorakhpur’
dt[‘mob no.’]=1234567890
print(‘the final updated dictionary is ‘,dt)
Program
person = {‘name’: ‘Ram‘} # key is not in the dictionary
salary = person.setdefault(‘salary’)
print(‘person = ‘,person)
print(‘salary = ‘,salary) # key is not in the dictionary
# default_value is provided
age = person.setdefault(‘age’, 22)
print(‘person = ‘,person)
print(‘age = ‘,age)
Example
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.pop(4))
print(squares)
print(squares.popitem())
print(squares)
del squares[3]
print(squares)
squares.clear()
print(squares)
del squares
print(squares) # Throws Error
Example
person = {‘name’: ‘Ram‘} # key is not in the dictionary
salary = person.setdefault(‘salary’)
print(‘person = ‘,person)
print(‘salary = ‘,salary) # key is not in the dictionary
# default_value is provided
age = person.setdefault(‘age’, 22)
print(‘person = ‘,person)
print(‘age = ‘,age)