Py Unit-2.2
Py Unit-2.2
-ABHILASH CHAKRABORTY
Sets in Python
A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements.
Python’s set class represents the mathematical notion of a set.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
Sets in Python
Frozen sets in Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied.
While elements of a set can be modified at any time, elements of the frozen set remain
the same after creation.
If no parameters are passed, it returns an empty frozen set.
Frozen Sets
Output:
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])
print("\nSet after Addition of elements using
Set after Addition of
Update: ")
elements using Update:
print(set1)
{10, 11, 4, 5, (6, 7)}
Using pop() method
copy() Returns a shallow copy of a set Returns the intersection of two sets
intersection()
as a new set
Removes and returns an arbitrary set Updates the set with the
pop() intersection_update()
element. Raise KeyError if the set is empty intersection of itself and another
Updates a set with the union of itself and Returns True if two sets have a null
update() isdisjoint()
others intersection
Function Description
issubset() Returns True if another set contains this set
Dictionary in Python is an unordered collection of data values, used to store data values
like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair.
Key value is provided in the dictionary to make it more optimized.
Creating a Dictionary
Output:
Dict = {1: ‘apple', 'name’: ‘Amit', 3: ‘Nile'}
They copy() method returns a shallow copy Produces a printable string representation of
copy() str()
of the dictionary. a dictionary.
Adds dictionary dict2’s key-values pairs to
The clear() method removes all items from update()
clear() dict
the dictionary.
Set dict[key]=default if key is not already in
setdefault()
dict
Removes and returns an element from a
pop() keys() Returns list of dictionary dict’s keys
dictionary having the given key.
items() Returns a list of dict’s (key, value) tuple pairs
Removes the arbitrary key-value pair from Returns true if key in dictionary dict, false
popitem() has_key()
the dictionary and returns it as tuple. otherwise
Create a new dictionary with keys from seq
It is a conventional method to access a fromkeys()
get() and values set to value.
value for a key.
type() Returns the type of the passed variable.
dictionary_nam returns a list of all the values available in a
e.values() given dictionary. cmp() Compares elements of both dict.