You are on page 1of 72

PYTHON PROGRAMMING

by C. RAJEEV
C. RAJEEVAssistant Professor,
Assist. Prof.Department of CSE,
Dept. of. CSE,
MRECW
MRECW.
UNIT III

Advanced Data Types: List, Tuple, Set, Frozenset, Dictionary, Range, Bytes & Bytearray,

None, List Data Structure, List indexing and splitting Updating List values, List Operations,

Iterating a List, Adding Elements to the List, Removing Elements from the List, List Built-in

Functions, List Built-in Methods, Tuple Data Structure, Tuple Indexing and Splitting, Tuple

Operations, Tuple Inbuilt Functions, Where use Tuple, List Vs Tuple, Nesting List and Tuple,

Set Data Structure, Creating a Set, Set Operations, Adding Items to the Set, Removing Items

from the Set, Difference Between discard() and remove(), Union of Two Sets, Intersection of

Two Sets, Difference of Two Sets, Set Comparisons, Frozenset Data Structure, Dictionary Data

Structure, Creating the Dictionary, Accessing the Dictionary Values, Updating Dictionary

Values, Deleting Elements Using del Keyword, Iterating Dictionary, Properties of Dictionary

Keys, Built-in Dictionary Functions, Built-in Dictionary Methods, List Vs Tuple Vs Set Vs

Frozenset Vs Dictionary Range, Bytes, Bytearray & None.


1. Advanced Data Types
1. List

2. Tuple

3. Dictionary

4. Set

5. Frozenset

6. Range

7. Bytes & Bytearray

8. None
1. List Data structure:
A list can be defined as a collection of values or items of different types.
It is used to store the sequence of various type of data.
The items in the list are separated with the comma (,) and enclosed with the
square brackets [].
List is a collection which is ordered and changeable.

How to Creating a list:


Syntax:
list = [value1, value2, value3,...valueN]
Ex:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Output: ['apple', 'banana', 'cherry']
print("creation of list")
# empty list
my_list = []
print(my_list)
# list of integers
my_list1 = [1, 2, 3,4,5,6,7,8,9]
print(my_list1)
# list with mixed datatypes
my_list2 = [1, "Hello", 3.4]
print(my_list2)
#nested list
Nested_list=[1, 'python', 5.5, 20, 'mrecw', (3+4j), 1, ['p', 2], 3]
How to Access Values in Lists:
Slicing works similar to strings; use the square bracket slice operator ([ ] ) along
with the index or indices.
How to access values in nested list:
>>> l1=[1,"python",5.5]
>>> l2=[20,"mrecw",3+4j]
>>> l3=[1,["p",2],3]
>>> tl=l1+l2+l3
>>> print(tl)
[1, 'python', 5.5, 20, 'mrecw', (3+4j), 1, ['p', 2], 3]
>>> print(tl[4])
mrecw
>>> print(tl[7][0])
p
How to Update List:
You can update single or multiple elements of lists by giving the slice on the
left-hand side of the assignment operator, and you can add to elements in a list
with the append() method:

>>> List = [1, 2, 3, 4, 5, 6]


>>> print(List)
[1, 2, 3, 4, 5, 6]
>>> List[2] = 10; // single element
>>> print(List)
[1, 2, 10, 4, 5, 6]

>>> List[1:3] = [89, 78] //multiple elements


>>> print(List)
How to add elements in the List:
you can add to elements in a list with the append() method.
Ex:
>>> List = [1, 2, 3, 4, 5, 6]
>>> print(List)
[1, 2, 3, 4, 5, 6]
>>> List.append(7)
>>> print(List)
[1, 2, 3, 4, 5, 6, 7]
How to Remove List Elements and Lists
To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do not
know.

>>> aList=[123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]

>>> del aList[1]


>>> aList
[123, 'float replacer', ['inner', 'list'], (7-9j)]

>>> aList.remove(123)
>>> aList
['float replacer', ['inner', 'list'], (7-9j)]
Iterating a List:
Using for loop:
Python for loop can be used to iterate through the List.
Example:
input_list = [10, "Safa", 15, "Aman", 1]
for x in input_list:
Output:
print(x)
10
Using while loop:
Safa
Python while loop can be used to iterate through the list.
15
Example:
Aman
input_list = [10, "Safa", 15, "Aman", 1]
1
length_list = len(input_list)
x=0
while x < length_list:
print(input_list[x])
x += 1
2. Tuple:
Tuple is a collection of items of any Python data type, same as the list type. Unlike the
list, tuple is immutable. i.e., the value of the items stored in the tuple cannot be
changed.

In tuple, we can store one or more items, of the same or different types, separated by
comma and enclosed in parentheses ().

How to Create and Assign Tuples:


# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
type(my_tuple) # Output: <class 'tuple'>
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple) # Output: (1, "Hello", 3.4)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) # Output: ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple[1][0]) # Output: 8
How to Access Values in Tuple:
Slicing works similarly to lists. Use the square bracket slice operator ( [ ] ) along with
the index or indices.
>>> a = (123, 'abc', 4.56, ['inner', 'tuple'], 7-9j)
>>> a[3]
['inner', 'tuple']
>>> a[1:4]
('abc', 4.56, ['inner', 'tuple'])
>>> a[:3]
(123, 'abc', 4.56)
>>> a[3][1]
'tuple'
>>> a[3][2]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a[3][2]
Backward index is also possible for accessing values.

>>> a = (123, 'abc', 4.56, ['inner', 'tuple'], 7-9j)


>>> a[-2]
['inner', 'tuple']
>>> a[-2][1]
'tuple'
>>> a[:-3]
(123, 'abc')
>>> a[-3]
4.56
How to Update Tuple:
Like numbers and strings, tuples are immutable, which means you cannot update them
or change values of tuple elements.
How to Remove Tuple Elements and Tuple:
Tuples are unchangeable, so you cannot remove items from it, but you can delete the
tuple completely.
>>> a=(1,'hi',30.5)
>>> del a[1]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
del a[1]
TypeError: 'tuple' object doesn't support item deletion

>>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a
NameError: name 'a' is not defined
Ex:
>>> t=(1,2,3,4) Cmp():
>>> max(t) In python2
In python3
4
>>> min(t) >>> t=(1,2,3)
>>> t=('a','b','c') >>> t1=('a','b','c')
1
>>> t1=(1,'p',2.5) >>> cmp(t,t1)
>>> t=('a','b','c')
>>> t==t1 -1
>>> max(t)
False >>> t=t1
'c'
>>> t=t1 >>> cmp(t,t1)
>>> min(t)
>>> t==t1 0
'a‘
True
>>> len(t)
3

Tuple(seq): (i.e., converting list into tuple)


>> aList = [123, 'xyz', 'zara', 'abc']
>>> aTuple = tuple(aList)
>>> type(aList)
<type 'list'>
>>> type(aTuple)
<type 'tuple'>
all():
It returns true if all elemets are true if false(either o or false) returns false.
For empty tuple it return true.
Ex:
>>> tuple=(1,2,3,4)
>>> print(all(tuple))
True

>>> tuple=(0,1,2,3,4)
>>> print(all(tuple))
False

>>> tuple=(1,2,3,4,True)
>>> print(all(tuple))
True

>>> tuple=(1,2,3,4,False)
>>> print(all(tuple))
False
>>> tuple=()
>>> print(all(tuple))
Any():
It returns true if any one element is true in the tuple.
For empty tuple it return False.
Ex:
>>> tup=(1,2)
>>> print(any(tup))
True

>>> tup=(1,2,True)
>>> print(any(tup))
True

>>> tup=(1,2,False)
>>> print(any(tup))
True

>>> tup=(0,False)
>>> print(any(tup))
False
>>> tup=()
>>> print(any(tup))
False
List vs Tuple
3. Dictionary/mapping type:
Dictionary is an unordered collection of items.

 Dictionary is used to store the data in a key-value pair format, other compound data
types have only value as an element.
Here, Keys must be a single element
Value can be any python object /datatype value, such as list, tuple, integer, etc.

Dictionary is mutable data-structure whereas the keys are the immutable python
object, i.e., it is unique.

Dictionary is used to simulate the real-life data arrangement where some specific
value exists for some particular key.
Creating the dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
An item has a key and the corresponding value expressed as a pair, key: value.

While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
Ex:
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
we can also create a dictionary using the built-in function dict().
# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
>>> type(my_dict)
<class 'dict'>
How to access elements from a dictionary?
While indexing is used with other container types to access values,
dictionary uses keys. Keys can be used either inside square brackets or with
the get() method.
Ex:
>>> my_dict = {'name':'Jack', 'age': 26}
>>> print(my_dict)
{'age': 26, 'name': 'Jack'}
>>> print(my_dict['name']) //using key
Jack
>>> print(my_dict['age'])
26
>>> print(my_dict.get('age')) // using get()
26
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
>>> print(my_dict.get('address'))
None
>>> print(my_dict['address'])
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
print(my_dict['address'])
KeyError: 'address‘

To prevent this type of error in python 2 we can check whether the specified key

existed or not by using has_key() (only in python2)


>>> my_dict.has_key('address')
False
>>> my_dict.has_key('age')
True
In python 3,we have to check using membership operator ‘in’
Ex:
>>>my_dict = {'name':'Jack', 'age': 26}
>>>print('age' in my_dict)
True
>>>print('address' in my_dict)
False

Creating nested values and accessing nested values:


>>> my_dict = {'name':'Jack', 'age': 26,'subjects':['python','ppl','cc']}
>>> print(my_dict)
{'age': 26, 'subjects': ['python', 'ppl', 'cc'], 'name': 'Jack'}
>>> print(my_dict['subjects'][0])
python
How to delete or remove elements from a dictionary ?
We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
Ex:
>>> my_dict = {'name':'Jack', 'age': 26,'subjects':['python','ppl','cc']}
>>> my_dict.pop('subjects')
['python', 'ppl', 'cc']
>>> print(my_dict)
{'name': 'Jack', 'age': 26}
 The popitem() method removes and returns the (key, value) pair from the dictionary
in the Last In, First Out (LIFO) order. popitem() doesn't take any parameters.
Ex:
>>> my_dict.popitem()
Note: Before Python 3.7, the popitem() method
('age’,:26)
returned and removed an arbitrary element (key, value)
>>> print(my_dict)
pair from the dictionary.
{'name': 'Jack'}
All the items can be removed at once using the clear() method but it returns empty dict ({})
Ex:
>>> my_dict.clear()
>>> print(my_dict)
{}
We can also use the del keyword to remove individual items or the entire dictionary itself.
Ex:
>>> my_dict = {'name':'Jack', 'age': 26}
>>> del my_dict['age']
>>> print(my_dict)
{'name': 'Jack'}
>>> del my_dict
>>> print(my_dict)
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
print(my_dict)
NameError: name 'my_dict' is not defined
How to change or add elements in a dictionary?
Dictionary are mutable. We can add new items or change the value of
existing items using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Ex:
>>> my_dict = {'name':'Jack', 'age': 26}
>>> my_dict['age'] = 27 //update
>>> print(my_dict)
{'age': 27, 'name': 'Jack'}
#adding elements
>>> my_dict['address'] = 'Downtown'
>>> print(my_dict)
{'age': 27, 'name': 'Jack', 'address': 'Downtown'}
Dictionary Built-in Methods
Copy():
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
o/p:
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}

items( ):
It returns a view object that displays a list of a given dictionary's (key, value)
tuple pair.
Ex:
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())
o/p:
[('apple', 2), ('orange', 3), ('grapes', 4)]
fromkeys()
The fromkeys() method creates a new dictionary from the given sequence of
elements with a value provided by the user.
Syntax:
dict.fromkeys(sequence[, value])
Ex:
>>> keys = {'a', 'e', 'i', 'o', 'u' }
>>> value = 'vowel‘ //provided by user
>>> vowels = dict.fromkeys(keys, value)
>>> print(vowels)
{'i': 'vowel', 'u': 'vowel', 'e': 'vowel', 'a': 'vowel', 'o': 'vowel'}
setdefault()
The setdefault() method returns the value of a key (if the key is in dictionary). If
not, it inserts key with a value to the dictionary.
Ex:
>>> person = {'name': 'Phill', 'age': 22}
>>> age = person.setdefault('age')
>>> salary = person.setdefault('salary')
>>> print('person = ',person)
('person = ', {'salary': None, 'age': 22, 'name': 'Phill'})
>>> print('Age = ',age)
('Age = ', 22)
>>> print('salary = ',salary)
('salary = ', None)
#or
salary = person.setdefault(‘salary', 20000)
update()
The update() method updates the dictionary with the elements from the another
dictionary object or from an iterable of key/value pairs.
Ex:
>>> d = {1: "one", 2: "three"}
>>> d1 = {2: "two"}
>>> d.update(d1)
>>> print(d)
{1: 'one', 2: 'two'} # updates the value of key 2
>>> d1 = {3: "three"}
>>> d.update(d1)
>>> print(d)
{1: 'one', 2: 'two', 3: 'three'} # adds element with key 3
Values():
It return new views of a dictionary values
Ex:
>>> d = {1: "one", 2: "three"}
>>> d.values()
dict_values(['one', 'three'])
Iterating over a dictionary in Python:
There are multiple ways to iterate over a dictionary in Python.
1. Iterate through all keys
2. Iterate through all values
3. Iterate through all key, value pairs
1. Iterate through all keys:
The order of states in the below code will change every time because the dictionary doesn’t
store keys in a particular order.
Program:
statesAndCapitals = { 'Gujarat' : 'Gandhinagar', 'Maharashtra' : 'Mumbai', 'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna’}
Output:
print('List Of given states:\n')
List Of given states:
# Iterating over keys
Rajasthan
for state in statesAndCapitals:
Bihar
print(state)
Maharashtra
Gujarat
In order to maintain the order of keys and values in a dictionary, use OrderedDict.
Program:
from collections import OrderedDict
statesAndCapitals = OrderedDict([ Output:
('Gujarat', 'Gandhinagar'), List Of given states:
('Maharashtra', 'Mumbai'), Gujarat
('Rajasthan', 'Jaipur'), Maharashtra
('Bihar', 'Patna') Rajasthan
]) Bihar
print('List Of given states:\n')
# Iterating over keys
for state in statesAndCapitals:
print(state)
2. Iterate through all values:
Again, in this case, the order in which the capitals are printed in the below code will
change every time because the dictionary doesn’t store them in a particular order.
Program:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai', Output:
'Rajasthan' : 'Jaipur', List Of given capitals:
'Bihar' : 'Patna' Gandhinagar
} Jaipur
print('List Of given capitals:\n') Mumbai
# Iterating over values Patna
for capital in statesAndCapitals.values():
print(capital)
3. Iterate through all key, value pairs:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna' Output:
} List Of given states and their capitals:
print('List Of given states and their capitals:\n‘ Bihar : Patna
# Iterating over values Gujarat : Gandhinagar
for state, capital in statesAndCapitals.items(): Rajasthan : Jaipur
print(state, ":", capital) Maharashtra : Mumbai
4. Set Data structure

A set is an unordered collection of items. Every element is unique (no duplicates).

Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.

Set does not support indexing slicing,concatentaion and repetition, but python having
mathematical set operations like union, intersection, difference and symmetric difference.

Set is mutable, we can add or remove items in the set. It has no hash value and cannot be
either a dictionary key or as an element of another set.
How to create a set?
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().

It can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
Ex:
#Creating a set with curly braces
# set of integers
>>> my_set = {1, 2, 3}
>>> my_set
set([1, 2, 3])
#creating a set using set()
>>> type(my_set)
>>> s=set([1,2,'a',2+4j,True])
<type 'set'>
>>> s
# set of mixed datatypes
set(['a', 1, 2, (2+4j)])
>>>my_set = {1.0, "Hello", (1, 2, 3)}
# set do not have duplicates
>>> my_set = {1,2,3,4,3,2}
>>> print(my_set)
set([1, 2, 3, 4])

# set cannot have a mutable element, like list, set or dictionary, as its element. but it contains
immutable element
# [3, 4] is a mutable list
my_set = {1, 2, [3, 4]}
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list‘
Set contains immutable element
>>>my_set = {1, 2, (3, 4)}
>>>my_set output: {(3, 4), 1, 2}
How to change a set in Python
sets are mutable, we cannot access or change an element of set using indexing or
slicing.

Ex:
>>> my_set = {1,3}
>>> print(my_set)
set([1, 3])

>>> my_set[0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
my_set[0]
TypeError: 'set' object does not support indexing
We can add single element using the add() method and multiple elements using
the update() method.

The update() method can take tuples, lists, strings or other sets as its argument. In all
cases, duplicates are avoided.
Ex:
>>> my_set.add(2) # add an element
>>> print(my_set)
set([1, 2, 3])
>>> my_set.update([2,3,4]) # add multiple elements
>>> print(my_set)
set([1, 2, 3, 4])
How to remove elements from a set?
A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not
exist in the set, it remains unchanged. But remove() will raise an error in such
condition.
>>> my_set = {1, 3, 4, 5, 6}
>>> my_set.discard(4)
>>> print(my_set)
set([1, 3, 5, 6])
>>> my_set.remove(6)
>>> my_set.remove(2)
>>> print(my_set)
Traceback (most recent call last):
set([1, 3, 5])
File "<pyshell#7>", line 1, in <module>
>>> my_set.discard(2)
my_set.remove(2)
>>> print(my_set)
KeyError: 2
set([1, 3, 5])
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped.
It is completely arbitrary.
We can also remove all items from a set using clear().

>>> my_set = set("HelloWorld")


>>> print(my_set)
{'d', 'e', 'l', 'H', 'o', 'r', 'W'} # Output: set of unique elements
>>> print(my_set.pop()) # pop an element
d # Output: first element
>>> print(my_set)
{'e', 'l', 'H', 'o', 'r', 'W'}
>>> my_set.clear() # clear my_set
>>> print(my_set)
set( )
2. Frozenset:
 frozen sets are just like sets but they can’t be changed. That is, frozen sets are the
immutable version of Python sets.
Ex:
>>> frozenset([1, 1, 2, 2, 3])
frozenset({1, 2, 3})
>>> frozenset('example')
frozenset({'l', 'p', 'x', 'm', 'e', 'a'})

The difference between set() and frozenset() in Python is in their mutablity only. frozenset()
is immutable and set() is mutable containing immutable objects.
Set: Frozen set:
>>> num = set([1, 2, 3])
>>> num = set([1, 2, 3])
>>> num.add(4)
>>> num.add(4)
>>> num Traceback (most recent call last):
{1, 2, 3, 4} File "<pyshell#17>", line 1, in <module>
num.add(4)
AttributeError: 'frozenset' object has no attribute 'add'
Set methods:
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
1. Set Union
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the method union().
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> A | B
set([1, 2, 3, 4, 5, 6, 7, 8])
Or
>>> A.union(B)
set([1, 2, 3, 4, 5, 6, 7, 8])
>>> B.union(A)
set([1, 2, 3, 4, 5, 6, 7, 8])
2.Set Intersection:
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection().

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> A & B
set([4, 5])
Or
>>> B.intersection(A)
set([4, 5])
>>> A.intersection(B)
set([4, 5]
3. Set Difference:
Difference of A and B (A - B) is a set of elements that are only in A those elements
are not common in B. Similarly, B - A is a set of element in B but not in A.
Difference is performed using - operator. Same can be accomplished using the
method difference().
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> A-B
set([1, 2, 3])
>>> B-A
set([6, 7,8])
Or
>>> A.difference(B)
set([1, 2, 3])
>>> B.difference(A)
set([6, 7,8])
4. Set Symmetric Difference
Symmetric Difference of A and B is a set of elements in both A and B except those
that are common in both.
Symmetric difference is performed using ^ operator. Same can be accomplished using
the method symmetric_difference().
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> A^B
set([1, 2, 3, 6, 7, 8])
>>> B^A
set([1, 2, 3, 6, 7, 8])
>>> A.symmetric_difference(B)
set([1, 2, 3, 6, 7, 8])
>>> B.symmetric_difference(A)
set([1, 2, 3, 6, 7, 8])
isdisjoint()
The isdisjoint() method returns True if two sets are disjoint sets. If not, it returns False.
Two sets are said to be disjoint sets if they have no common elements.
>>> A = {1, 2, 3, 4}
>>> B = {5, 6, 7}
>>> C = {4, 5, 6}
>>> A.isdisjoint(B)
True
>>> A.isdisjoint(C)
False
issubset()
The issubset() method returns True if all elements of a set are present in another set If
not, it returns False.
Set A is said to be the subset of set B if all elements of A are in B .
>>> A = {1, 2, 3}
>>> B = {1, 2, 3, 4, 5}
>>> C = {1, 2, 4, 5}
>>> A.issubset(B)
True
>>> B.issubset(A)
False
>>> C.issubset(B)
True
issuperset():
The issuperset() method returns True if a set has every elements of another set If not,
it returns False.
Set A is said to be the superset of set B if all elements of B are in A.
>>> A = {1, 2, 3, 4, 5}
>>> B = {1, 2, 3}
>>> C = {1, 2, 3}
>>> A.issuperset(B)
True
>>> B.issuperset(A)
False
>>> C.issuperset(B)
True
Set Membership Test
We can test if an item exists in a set or not, using the keyword in
>>> my_set = set("apple")
>>> 'a' in my_set
True
>>> 'p' not in my_set
False
5. Frozen set:
 frozen sets are just like sets but they can’t be changed. That is, frozen sets are the
immutable version of Python sets.
Ex:
>>> frozenset([1, 1, 2, 2, 3])
frozenset({1, 2, 3})
>>> frozenset('example')
frozenset({'l', 'p', 'x', 'm', 'e', 'a'})

The difference between set() and frozenset() in Python is in their mutablity only. frozenset()
is immutable and set() is mutable containing immutable objects.
Set: Frozen set:
>>> num = set([1, 2, 3])
>>> num = set([1, 2, 3])
>>> num.add(4)
>>> num.add(4)
>>> num Traceback (most recent call last):
{1, 2, 3, 4} File "<pyshell#17>", line 1, in <module>
num.add(4)
AttributeError: 'frozenset' object has no attribute 'add'
6. range():
This function in Python is used to generate a sequence of numbers, similar to the
xrange() function. However, xrange() is used only in Python 2.x whereas range() is used
in Python 3.x.

We can generate a sequence of numbers using range() function.

range(10) will generate numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start, stop, step size).
step size defaults to 1 if not provided.

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
7. byte datatype:
The bytes() function returns a bytes object.
It can convert objects into bytes objects, or create empty bytes object of the specified
size.
It is immutable ( object that cannot be modified,) sequence of small integers in the
range 0 <= x < 256. print as ASCII characters when displayed.

Syntax:
bytes(x, encoding, error)
x------------- 1. A source to use when creating the bytes object.
2. If it is an integer, an empty bytes object of the specified size
will be created.
3. If it is a String, make sure you specify the encoding of the
source.
Encoding-------------The encoding of the string
Error-----------------Specifies what to do if the encoding fails.
Ex: 1
#Create a byte of given integer size
size = 5 Output
arr = bytes(size) b'\x00\x00\x00\x00\x00'
print(arr)

Ex: 2
#Convert string to bytes
string = "Python is interesting.”
Output:
# string with encoding 'utf-8'
b'Python is interesting.'
arr = bytes(string, 'utf-8')
print(arr)
Ex: 3
#Convert iterable list to bytes
rList = [1, 2, 3, 4, 5]
arr = bytes(rList)
print(arr)

Output:
b'\x01\x02\x03\x04\x05'
8. bytearray datatype:
bytearray is same as byte data type, only difference is its mutability.
The bytearray() function returns a bytes object.
It can convert objects into bytearray objects, or create empty bytes object of the
specified size.
It is mutable ( object that can be modified,) sequence of small integers in the range 0
<= x < 256. print as ASCII characters when displayed.
Syntax:
bytearray(x, encoding, error)
x------------- 1. A source to use when creating the bytes object.
2. If it is an integer, an empty bytes object of the specified size
will be created.
3. If it is a String, make sure you specify the encoding of the
source.
Encoding-------------The encoding of the string
Error-----------------Specifies what to do if the encoding fails.
Ex: 1
# Array of bytes of given integer size
size = 5 Output
arr = bytearray(size) bytearray(b'\x00\x00\x00\x00\x00')
print(arr)

Ex: 2
# Array of bytes from a string
string = "Python is interesting.”
Output:
# string with encoding 'utf-8'
bytearray(b'Python is interesting.')
arr = bytearray(string, 'utf-8')
print(arr)
Ex: 3
# Array of bytes from an iterable list
rList = [1, 2, 3, 4, 5]
arr = bytearray(rList)
print(arr)

Output:
bytearray(b'\x01\x02\x03\x04\x05’)
Note: The acronym codec stands for COder/DECoder. It is a specification for encoding
text as byte values and decoding those byte values into text. Unlike ASCII, which used
only one byte to encode a character into a number, Unicode uses multiple bytes. Plus
Unicode supports several different ways of encoding characters into bytes. The most
popular is UTF-8, which uses one byte to encode all the characters in ASCII. For other
characters, UTF-8 may use one or four bytes to represent a letter, three (mainly) for
CJK/East Asian characters, and four for some rare, special use, or historic characters.
9. Null object ( None ):Python's Null Object
 Python has a special type known as the Null object or NoneType

 It has only one value, None . The type of None is NoneType .

 It does not have any operators or BIFs.

If you are familiar with C, the closest analogy to the None type is void,

while the None value is similar to the C value of NULL.

Ex:

>>> x=None

>>> print(x)

None

>>> type(x)

<class 'NoneType'>

None has no (useful) attributes and always evaluates to having a Boolean False value.
int vs float vs complex vs bool vs str vs bytes vs bytearray vs range vs list vs tuple
vs set vs frozenset vs dictionary

You might also like