Data Types in Python (1)
Data Types in Python (1)
Syllabus
• String
• Numeric
• List
• Tuples
• Dictionary
• Set
• Bool
• Mutable and Immutable Data types.
2
Data Types
Data type is the classification of the type of values that can be assigned to variables
7/21/2022 3
Standard Data Types in Python
In Python, we don’t need to declare a variable with explicitly mentioning the data type, but it’s still
important to understand the different types of values that can be assigned to variables in Python. After all
the data type of a variable is decided based on the value assigned.
7/21/2022 4
Standard Data Types in Python
7/21/2022 5
Python Data Type: Number
• Python supports three different numerical types
• int (signed integers) a=20;
• float (floating point real values) b=15.45
• complex (complex numbers) c=3.14j
7/21/2022 6
Python Data Type: Number
a, b, c = 1, 2, 3
print(a,b,c)
a, b, _ = 1, 2, 3
print(a, b)
a, b, c = 1, 2
print(a,b,c)
ValueError
7/21/2022 7
Python Data Type: Strings
Strings: Strings in Python are used to store textual information
A string is a sequence of characters. E.G. ‘MITWPU’ “Pune”
A character is simply a symbol. For example, the English language has 26 characters.
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows either pair of single or double quotes.
#defining strings in Python . # all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Pune"
print(my_string)
str[22] str1="python"
IndexError: string index out of range print(str1)
# index must be an integer
str[2.2] print(str1)
...
TypeError: string indices must be integers #del str
print(str1)
str="python"
print(str) We cannot delete or remove characters from a string
str="python"
str[1]=q
print(str)
7/21/2022 10
Python String Operations
String Membership Test
Concatenation of Two or More Strings 't' in 'mitwpu pune‘
# Python String Operations ‘x' in 'mitwpu pune‘
str1 = 'Hello'
str2 ='World!' Built-in functions to Work with Python
enumerate() and len(). The enumerate() function returns an enumerate object.
# using + It contains the index and value of all the items in the string as pairs. This can be
print('str1 + str2 = ', str1 + str2) useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
# using * str = 'MITWPU'
print('str1 * 3 =', str1 * 3) # enumerate()
xx = list(enumerate(str))
# Iterating through a string print('list(enumerate(str) = ',xx)
count = 0
for x in 'Hello World': #character count
if(x == 'l'): print('len(str) = ', len(str))
count += 1
print(count,'letters found')
7/21/2022 Data Science 11
Common Python String Methods
Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace()
"MITwpu".upper()
"MITwpu".lower()
• Tuple data type in Python is a collection of various immutable Python objects separated by commas.
• Tuples are much similar to Python Lists, but they are syntactically different, i.e., in lists we use
square brackets while in tuples we use parentheses.
• The main difference between Python tuples and lists is that the elements of a tuple cannot be
changed once they are assigned; whereas, the elements of a list can be changed.
• Iteration in a tuple is faster as compared to lists since tuples in Python are immutable
• Whenever, we need to make sure that the data remains unchanged and write protected, Python
tuple is the best option.
7/21/2022 14
Python Data Type: tuples
tup1 = ("Petroleum", " Polymer", "Chemical") t = 'a', 'b', 'c', 'd', 'e'
tup2 = 1,2,3,4 print(t)
print (tup1) type(t)
print (tup2)
t1=()
print(tup1[1]) print(t1)
print(tup1[-1]) type(t1)
7/21/2022 15
Python Data Type: lists
7/21/2022 16
Python Data Type: lists
7/21/2022 17
Python Data Type: lists
7/21/2022 18
Python Data Type: lists
7/21/2022 19
Python Data Type: lists
sample_list=[]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)
7/21/2022 20
Python Data Type: lists
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
7/21/2022 22
Python Data Type: lists
print(odd)
print(my_list.pop(1))
print(my_list)
print(my_list.pop())
print(my_list)
my_list.clear()
print(my_list)
7/21/2022 25
Python Data Type: lists
print(my_list.index(8))
print(my_list.count(8))
my_list.sort()
print(my_list)
my_list.reverse()
print(my_list)
my_list.clear()
print(my_list)
7/21/2022 26
Python Data Type: lists
7/21/2022 27
Python Data Type: lists
List Membership Test
*** List Comprehension:
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
pow2 = [2 ** x for x in range(10)]
print(pow2) # Output: True
equivalent to: print('p' in my_list)
pow2 = []
for x in range(10): # Output: False
pow2.append(2 ** x) print('a' in my_list)
print(pow2)
# Output: True
pow2 = [2 ** x for x in range(10) if x > 5] print('c' not in my_list)
print(pow2)
Iterating Through a List
odd = [x for x in range(20) if x % 2 == 1] for fruit in ['apple','banana','mango']:
print(odd) print("I like",fruit)
7/21/2022 28
Python Data Type: Dictionary
• Python Dictionaries is an unordered collection of data.
• The data in the dictionary is stored as a key: value pair where the key should not be mutable and value can
be of any type.
• In List …single value is stored…in dictionary has pair {key and its value}
Creating a Dictionary:
people ={"Rajendra":33,"Amit":32,"Amol":42}
print(people)
# dictionary is mutable
people['Amol']=50
print(people)
#Accessing elements from a dictionary
print(people["Amit"])
print(" Age of amol from dictionary ",people["Amol"])
#Removing elements from a dictionary
del people[‘Amit’]
print(people)
7/21/2022 29
Python Data Type: Dictionary
Dictionary Functions:
1. Key present in dictionary or not
numbers= {1:"Rajendra",2:"Amol",3:"Hanmant"}
print(2 in numbers)
numbers= {1:"Rajendra",2:"Amol",3:"Hanmant"}
print(5 in numbers)
*** 2. .get() function gives values of particular key if present else gives by default None op if key is not present
Syntax: dictionayname.get (key value)
numbers= {1:"Rajendra",2:"Amol",3:"Hanmant"}
7/21/2022 30
Python Data Type: Dictionary
Dictionary Functions:
Loop Through a Dictionary in Python
To iterate through a dictionary, we can use the Python for loop
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
for i in cubes:
print(cubes[i])
Remove Items from a Dictionary and Delete the Whole Dictionary in Python
• We use the pop() Python Function to remove a particular element from a dictionary
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
print(cubes.pop(4))
print(cubes)
Remove Elements Using the popitem() Method:
• We can use the popitem() method to remove any randomly picked element
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
print(cubes.popitem())
print(cubes)
Remove Items Using the del Keyword in a Dictionary:
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
del cubes[2]
print (cubes)
7/21/2022 31
Python Data Type: Dictionary
Dictionary Functions:
Delete All Elements Using the Clear() Method:
We can use the clear() method,
and it will clear out or delete all elements from a dictionary at once
7/21/2022 33
Common Python Dictionary Methods:
Method Description
clear() It removes all elements from a dictionary.
copy() It returns a copy of a dictionary.
fromkeys() It returns a dictionary with the specified keys and values.
get() It returns the value of a specified key.
items() It returns a list containing a tuple for each key–value pair.
keys() It returns a list containing the dictionary’s keys.
pop() It removes an element with a specified key.
popitem() It removes the last inserted (key, value) pair.
setdefault() It returns the value of a specified key.
update() It updates a dictionary with the specified key–value pairs.
values() It returns a list of all values in a dictionary.
7/21/2022 35
Python Data Type: Set
7/21/2022 36
Python Data Type: Set
# Sets - They are mutable and new elements can be added once sets are defined
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # duplicates will be removed
num={1,4,7,9,5,4}
print(num)
a = set('abracadabra')
print(a)
# Using the in-built set() method with the elements that we want to add as the parameters
myset = set(("apple","banana","cherry")) # note the double round-brackets
print(myset)
7/21/2022 37
Python Data Type: Set
# Adding Elements to a Set in Python
# 1. Using the add() method
myset = {'apple', 'banana','cherry'}
myset.add("orange")
print(myset)
# 2. Using update()
myset = {'apple', 'banana','cherry'}
myset.update(["orange","mango","grapes"])
print(myset)
7/21/2022 39
Introduction
• The NumPy library is a popular Python library used for scientific computing
applications, and is an acronym for "Numerical Python".
• NumPy's operations are divided into three main categories: Fourier Transform and
Shape Manipulation, Mathematical and Logical Operations, and Linear Algebra and
Random Number Generation. To make it as fast as possible, NumPy is written in C and
Python.
Advantages of NumPy
• NumPy has several advantages over using core Python mathemtatical functions, a few
of which are outlined here:
• NumPy is extremely fast when compared to core Python thanks to its heavy use of C
extensions.
• Many advanced Python libraries, such as Scikit-Learn, Scipy, and Keras, make
extensive use of the NumPy library. Therefore, if you plan to pursue a career in data
science or machine learning, NumPy is a very good tool to master.
• NumPy comes with a variety of built-in functionalities, which in core Python would
take a fair bit of custom code. 40
(1) ndarray.ndim
ndim represents the number of dimensions (axes) of the ndarray.
e.g. for this 2-dimensional array [ [3,4,6], [0,8,1]], value of ndim will be 2. This ndarray has two dimensions
(axes) - rows (axis=0) and columns (axis=1)
(2) ndarray.shape
shape is a tuple of integers representing the size of the ndarray in each dimension.
e.g. for this 2-dimensional array [ [3,4,6], [0,8,1]], value of shape will be (2,3) because this ndarray has two
dimensions - rows and columns - and the number of rows is 2 and the number of columns is 3
(3) ndarray.size
size is the total number of elements in the ndarray. It is equal to the product of elements of the shape. e.g. for this
2-dimensional array [ [3,4,6], [0,8,1]], shape is (2,3), size will be product (multiplication) of 2 and 3 i.e. (2*3) =
6. Hence, the size is 6.
(4) ndarray.dtype
dtype tells the data type of the elements of a NumPy array. In NumPy array, all the elements have the same data
type.
e.g. for this NumPy array [ [3,4,6], [0,8,1]], dtype will be int64
(5) ndarray.itemsize
itemsize returns the size (in bytes) of each element of a NumPy array.
e.g. for this NumPy array [ [3,4,6], [0,8,1]], itemsize will be 8, because this array consists of integers and size of
integer (in bytes) is 8 bytes.
41
42