2. 2
What is Data Type?
A data type, in programming, is a classification that specifies which type of value a variable
has and what type of mathematical, relational or logical operations can be applied to it
without causing an error.
The "type" of a particular variable or constant determines how many bits are used used for
that paticular data item, and how the bits are to be interpreted.
Python is a dynamically typed language; hence we do not need to define the type of the
variable while declaring it. The interpreter implicitly binds the value with its type.
Python enables us to check the type of the variable used in the program. It provides us the
type() function, which returns the type of the variable passed.
4. 4
Numbers
Number stores numeric values.
The integer, float, and complex values
belong to a Python Numbers data-type.
Python provides the type() function to
know the data-type of the variable.
Similarly, the isinstance() function is
used to check an object belongs to a
particular class.
Python creates Number objects when a
number is assigned to a variable.
5. 5
Numeric Data Types- Classification
Python supports three types of numeric data.
Int - Integer value can be any length such as
integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value
belongs to int
Float - Float is used to store floating-point
numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.
complex - A complex number contains an ordered
pair, i.e., x + iy where x and y denote the real and
imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.
Int
Numeric Data Type
ComplexFloat
6. 6
Dictionary
Dictionary is an unordered set of a
key-value pair of items.
It is like an associative array or a
hash table where each key stores a
specific value. Key can hold any
primitive data type, whereas value
is an arbitrary Python object.
The items in the dictionary are
separated with the comma (,) and
enclosed in the curly braces {}.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
7. 7
Boolean Data Type
Boolean type provides two built-in values, True and False.
These values are used to determine the given statement true or false.
It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false
can be represented by the 0 or 'F'
8. 8
Set
Python Set is the unordered
collection of the data type.
It is iterable, mutable(can modify
after creation), and has unique
elements.
In set, the order of the elements is
undefined; it may return the
changed sequence of the element.
The set is created by using a built-
in function set(), or a sequence of
elements is passed in the curly
braces and separated by the
comma.
It can contain various types of
values.
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)
9. 9
Sequence Data Types- Classification
Python supports three types of sequence data.
String - Strings in Python are identified as a
contiguous set of characters represented in the
quotation marks. Python allows for either pairs of
single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string
and working their way from -1 at the
List - Lists are the most versatile of Python's
compound data types. A list contains items
separated by commas and enclosed within square
brackets ([]).
Tuple - A tuple is another sequence data type that is
similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses
String
Sequence Data Type
TupleList
10. 10
String Data Type
The string can be defined as the sequence of characters represented in the quotation marks.
In Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions
and operators to perform operations in the string.
In the case of string handling, the operator + is known as concatenation operator and is used
to concatenate two strings as the operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
11. 11
String Data Type- Example
str1 = 'Hello Students' #string str1
str2 = ' Welcome to Python World' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
12. 12
List Data Type
A list in Python is used to store the sequence of
various types of data.
Python lists are mutable type its mean we can
modify its element after it is created.
A list can be defined as a collection of values or
items of different types. The items in the list are
separated with the comma (,) and enclosed with the
square brackets [ ].
We can use slice [:] operators to access the data of
the list.
The concatenation operator (+) and repetition
operator (*) works with the list in the same way as
they were working with the strings.
13. 13
Characteristics of List
The list has the following characteristics:
The lists are ordered.
The element of the list can access by index.
The lists are the mutable type. It means the list-items can be updated, added or
removed when required.
A list can store the number of various elements.
14. 14
List indexing and splitting
The indexing is processed in the same way as it happens with the strings. The elements of the list
can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index,
the second element of the list is stored at the 1st index, and so on.
Python provides the flexibility to use the negative indexing also. The negative indices are counted
from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
Ex: list=[1,2,3,4,5]
List-items 1 2 3 4 5
Forward Direction
Index value
0 1 2 3 4
Backward
direction Index
Value
-5 -4 -3 -2 -1
Accessing items using
index
Slicing of list
list[0]=1 list[0:]=[1,2,3,4,5]
list[1]=2 list[:]=[1,2,3,4,5]
list[2]=3 list[2:4]=[3,4,5]
list[3]=4 list[1:]=[2,3,4,5]
list[4]=5 list[:3]=[1,2,3,4]
15. 15
Creating a sub-list in Python
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
The start denotes the starting index position of the list.
The stop denotes the last index position of the list.
The step is used to skip the nth element within a start:stop
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from
the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
16. 16
List Funtions/Methods:
Following are the different functions supported by list.
cmp()
len()
max()
min()
list()
append()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()
17. 17
List cmp() method
cmp() compares elements of two lists.
It takes two arguments.
If elements are of the same type, perform the
compare and return the result. If elements are
different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary
and compare.
If either element is a number, then the other
element is "larger" (numbers are "smallest").
Otherwise, types are sorted alphabetically by
name.
If we reached the end of one of the lists, the
longer list is "larger." If we exhaust both lists and
share the same data, the result is a tie, meaning
that 0 is returned.
Syntax:
cmp(list1,list2)
Example:
input
list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
output
-1
1
-1
18. 18
List method
len() returns the number of elements in the list.
max() returns the elements from the list with
maximum value.
min() returns the elements from the list with
minimum value.
list() converts a tuple into list.
Syntax:
len(list_name)
max(list_name)
min(list_name)
list(sequence)
Example:
list1= [123, 456, 700, 200]
print ("Length of list1 : ", len(list1))
print ("Max value element : ",
max(list1))
print ("Min value element : ", min(list1))
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print("List elements : ", aList)
19. 19
List method
Sr.No. Methods Name Description
1 append(obj) Appends object obj to list
2 count(obj) Returns count of how many times obj occurs in list
3 extend(seq) Appends the contents of seq to list
4 index(0bj) Returns the lowest index in list that obj appears
5 insert(index,obj) Inserts object obj into list at offset index
6 pop() Removes and returns last object or obj from list
7 remove(obj) Removes object obj from list
8 reverse() Reverses objects of list in place
9 sort() Sorts objects of list, use compare func if given
21. 21
Tuple Data Type
Python Tuple is used to store the sequence of immutable Python objects.
The tuple is similar to lists since the value of the items stored in the list can be changed, whereas
the tuple is immutable, and the value of the items stored in the tuple cannot be changed
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. The empty tuple is written as two
parentheses containing nothing
tup1 = (“c”,”python”,”c++”)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ‘a’,’b’,’c’
tup4=()
Note: The tuple which is created without using parentheses is also known as tuple packing.
22. 22
Accessing Values in Tuple
To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
23. 23
Tuple indexing and splitting
The indexing is processed in the same way as it happens with the strings. The elements of the
tuple can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the tuple is stored at the 0th
index, the second element of the tuple is stored at the 1st index, and so on.
Python provides the flexibility to use the negative indexing also. The negative indices are counted
from the right. The last element (rightmost) of the tuple has the index -1; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
Ex: tup=(1,2,3,4,5)
Tuple-items 1 2 3 4 5
Forward Direction
Index value
0 1 2 3 4
Backward
direction Index
Value
-5 -4 -3 -2 -1
Accessing items using
index
Slicing of list
tup[0]=1 tup[0:]=(1,2,3,4,5)
tup[1]=2 tup[:]=(1,2,3,4,5)
tup[2]=3 tup[2:4]=(3,4,5)
tup[3]=4 tup[1:]=(2,3,4,5)
tup[4]=5 tup[:3]=(1,2,3,4)
24. 24
Tuple’s built-in method
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is
greater than tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
25. 25
Basic Tuple Operations
The operators like concatenation (+), repetition (*), Membership (in) works in the same way as
they work with the list. Consider the following table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
Repetition The repetition operator enables the tuple
elements to be repeated multiple times.
t*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Concatenation It concatenates the tuple mentioned on either
side of the operator.
t1+t2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Membership It returns true if a particular item exists in the
tuple otherwise false
print (2 in t1) prints True.
Iteration The for loop is used to iterate over the tuple
elements.
for i in t1: print(i)
Length It is used to get the length of the tuple. len(t1) = 5
26. 26
Uses of Tuple Data Type
Using tuple instead of list is used in the following scenario.
Using tuple instead of list gives us a clear idea that tuple data is constant and must not be
changed.
Tuple can simulate a dictionary without keys. Consider the following nested structure, which can
be used as a dictionary.
[(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]
27. 27
Deletion operation of Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
28. 28
List vs Tuple
SN List Tuple
1 The literal syntax of list is shown by the
[].
The literal syntax of the tuple is shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality
than a tuple.
The tuple provides less functionality than the list.
5 The list is used in the scenario in which
we need to store the simple collections
with no constraints where the value of
the items can be changed.
The tuple is used in the cases where we need to store
the read-only collections i.e., the value of the items
cannot be changed. It can be used as the key inside
the dictionary.
6 The lists are less memory efficient than
a tuple.
The tuples are more memory efficient because of its
immutability.
29. 29
Dictionary
Python Dictionary is used to store the data in a key-value pair format.
The dictionary is the data type in Python, which can simulate the real-life data arrangement
where some specific value exists for some particular key.
It is the mutable data-structure.
The dictionary is defined into element Keys and values.
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.
30. 30
How to Create a Dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).
Syntax: dict={key1:val1, key2:val2, …., keyn:valn}
31. 31
How to Create a Dictionary
Python provides the built-in function dict() method which is also used to create dictionary. The
empty curly braces {} is used to create empty dictionary.
Syntax: dict={ } # empty dictionary
dict=({key1:val1, key2:val2,..,keyn:valn})
dict=([(key1,val1),(key2,val2),…,(keyn,valn)])
32. 32
Accessing values from dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys
can be used either inside square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary.
On the other hand, the get() method returns None if the key is not found.
33. 33
Changing and Updating dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
34. 34
Deleting dictionary elements
We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair
from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
35. 35
Dictionary Methods
Sr.No. Function Description
1 cmp(dict1, dict2) Compares elements of both dict.
2 len(dict) Gives the total length of the dictionary. This
would be equal to the number of items in the
dictionary.
3 str(dict) Produces a printable string representation of
a dictionary
4 type(variable) Returns the type of the passed variable. If
passed variable is dictionary, then it would
return a dictionary type.
36. 36
Dictionary Methods
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key[,d])
Removes the item with the key and returns its value or d if key is not found. If d is not
provided and the key is not found, it raises KeyError.
popitem()
Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary
is empty.
setdefault(key[,d])
Returns the corresponding value if the key is in the dictionary. If not, inserts the key
with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values
37. 37
Boolean Data Type
Boolean type provides two built-in values, True and False.
These values are used to determine the given statement true or false.
It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false
can be represented by the 0 or 'F'
38. 38
Set Data Type
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed). It can contain any type of element such as integer, float,
tuple etc. But mutable elements (list, dictionary, set) can't be a member of set.
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
39. 39
Creating Set in Python
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}.
Python also provides the set() method, which can be used to create the set by the passed
sequence.
Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday"
, "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday
", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
40. 40
Adding items in Set
Python provides the add() method and update() method which can be used to add some
particular item to the set. The add() method is used to add a single element whereas the
update() method is used to add multiple elements to the set. Consider the following example.
Example 1: Using Add Method
Months=set(["January","February","March","April",
"May","June"])
print("nprinting the original set ... ")
print(Months)
print("nAdding other months to the set...")
Months.add("July")
Months.add("August")
print("nPrinting the modified set...")
print(Months)
Example 2: Using update() method
Months=set(["January","February","March","Apr
il","May","June"])
print("nprinting the original set ... ")
print(Months)
print("nupdating the original set ... ")
Months.update(["July","August","September","
October"])
print("nprinting the modified set ... ")
print(Months)
41. 41
Removing items from the Set
Python provides the discard() method and remove() method which can be used to remove the
items from the set.
The difference between these function, using discard() function if the item does not exist in the
set then the set remain unchanged whereas remove() method will through an error.
Example 1: Using discard() Method
months=set(["January","February","March","April",
"May","June"])
print("nprinting the original set ... ")
print(months)
print("nRemoving some months from the set...")
months.discard("January")
months.discard("May")
print("nPrinting the modified set...")
print(months)
Example 2: Using remove() method
months=set(["January","February","March","April
","May","June"])
print("nprinting the original set ... ")
print(months)
print("nRemoving some months from the set...")
months.remove("January")
months.remove("May")
print("nPrinting the modified set...")
print(months)
42. 42
Removing items from the Set
We can also use the pop()
method to remove the item.
Generally, the pop() method
will always remove the last
item but the set is unordered,
we can't determine which
element will be popped from
set.
Python provides the clear()
method to remove all the items
from the set.
43. 43
Operations on Sets
Union Intersection Difference
The union of two sets is
calculated by using the pipe
(|) operator.
The union of the two sets
contains all the items that are
present in both the sets.
The intersection of two sets
is calculated by using the
and (&) operator.
The intersection of the two
sets is given as the set of
the elements that common
in both sets..
The difference of two sets can
be calculated by using the
subtraction (-) operator
or intersection() method.
Suppose there are two sets A
and B, and the difference is A-B
that denotes the resulting set
will be obtained that element of
A, which is not present in the set
B.