0% found this document useful (0 votes)
9 views

Data Types in Python (1)

Uploaded by

Kranium A
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Data Types in Python (1)

Uploaded by

Kranium A
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Python Programming

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.

Python data types are categorized into two as follows:


•Mutable Data Types:
Data types in python where the value assigned to a variable can be changed
•Immutable Data Types:
Data types in python where the value assigned to a variable cannot be changed

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)

my_string = '''MITWPU '''


print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python programming"""
print(my_string)
7/21/2022 8
Python Data Type: Strings
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator

#Accessing string characters in Python


str = 'Python Programming'
str[22]
print('str = ', str)
IndexError: string index out of range
#first character # index must be an integer
print('str[0] = ', str[0]) str[2.2]
...
#last character TypeError: string indices must be integers
print('str[-1] = ', str[-1])
str="python"
#slicing 2nd to 5th character print(str)
print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2])
7/21/2022 9
Python Data Type: Strings

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)

Strings are immutable. This means that elements of a


string cannot be changed once they have been assigned

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()

"This will split all words into a list".split()

' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])

'Welcome to MITWPU Pune'.find('co')

'Happy New Year'.replace('Happy','Brilliant')

7/21/2022 Data Science 12


Python Data Type: tuples

7/21/2022 Data Science 13


Python Data Type: tuples

• 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.

• Tuples can be thought of as read-only lists

• 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)

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) t1 = 'a',


tinytuple = (123, 'john') type(t1)
print (tuple)
print (tinytuple)
print (tuple + tinytuple)

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=[]

List can store both homogeneous and heterogeneous elements


# list of integers
my_list = [1, 2, 3]

# list with mixed data types


my_list = [1, "Hello", 3.4]

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)

Creating a list with known size and unknown elements


sample_list=[None]*5
print(sample_list)

7/21/2022 20
Python Data Type: lists

my_list = ['p', 'r', 'o', 'b', 'e']


# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing


print(my_list[4.0])
7/21/2022 21
Python Data Type: lists
Negative indexing in lists # List slicing in Python
my_list = ['p','r','o','b','e']
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[-1])
# elements 3rd to 5th
print(my_list[-5]) print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

7/21/2022 22
Python Data Type: lists

# Correcting mistake values in a list # Appending and Extending lists in Python


odd = [2, 4, 6, 8] odd = [1, 3, 5]
print(odd)
odd.append(7)
# change the 1st item
odd[0] = 1 print(odd)

print(odd) odd.extend([9, 11, 13])

# change 2nd to 4th items print(odd)


odd[1:4] = [3, 5, 7]

print(odd)

7/21/2022 Data Science 23


Python Data Type: lists
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# Concatenating and repeating lists
odd = [1, 3, 5] # delete one item
del my_list[2]
print(odd + [9, 7, 5])
print(my_list)
print(["re"] * 3)
# delete multiple items
# Demonstration of list insert() method
del my_list[1:5]
insert(index, value) – inserts value just before the specified index.
Thus after the insertion the new element occupies position index.
print(my_list)
odd = [1, 9]
odd.insert(1,3)
# delete entire list
del my_list
print(odd)
# Error: List not defined
odd[2:2] = [5, 7,6]
print(my_list)
print(odd)
7/21/2022 24
Python Data Type: lists
We can use remove() method to remove the given item or pop() method to remove an item at the given index.
** The pop() method removes and returns the last item if the index is not provided.
This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)

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

# Python list methods …index(), count(),sort(),reverse(),clear()


my_list = [3, 8, 1, 6, 0, 8, 4]

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"}

print(numbers.get(1)) #.get(key) gives values of that key op: Rajendra


print(numbers.get(5)) # gives none if key is not in dictionary op: None

# gives avoid none by default as key is not present.. print msg


print(numbers.get(5," Key is not present msg"))
print(numbers.get(1," Key is not present msg"))

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

cubes = {1:1, 2:8, 3:21, 4:64, 5:125} # It returns a copy of a dictionary.


cubes.clear() t=cubes.copy()
print(cubes) print(t)
#It returns a list containing the dictionary’s keys.
Deleting the Whole Dictionary k=cubes.keys()
cubes = {1:1, 2:8, 3:21, 4:64, 5:125} print(k)
print(cubes) #It returns a list of all values in a dictionary.
v=cubes.values()
del cubes print(v)
print(cubes) #It returns the value of a specified key.
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
Python Dictionary Length cubes.setdefault(4)
To check the length of the dictionary,
cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
print(len(cubes))
7/21/2022 32
Python Data Type: Dictionary

#It updates a dictionary with the specified key–value pairs.


d = {1: "one", 2: "three"}
print(d)
d1 = {2: "two"}

# updates the value of key 2


d.update(d1)
print(d)
# It returns a list containing a tuple for each key–value pair.
cubes = {1:1, 2:8, 3:27, 4:64, 5:125}
print(cubes.items())

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 Data Science 34


Python Data Type: Set

7/21/2022 35
Python Data Type: Set

#It updates a dictionary with the specified key–value pairs.


d = {1: "one", 2: "three"}
print(d)
d1 = {2: "two"}

# updates the value of key 2


d.update(d1)
print(d)
# It returns a list containing a tuple for each key–value pair.
cubes = {1:1, 2:8, 3:271, 4:64, 5:125}
print(cubes.items())

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 commas to separate and curly braces to group elements


myset = {'apple', 'banana','cherry'}
print(myset)

# 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)

# Removing elements from sets in Python 3. Using pop():


1. Using the remove() method: myset = {"apple","banana","cherry"}
myset = {'apple', 'banana','cherry'} x = myset.pop()
myset.remove("banana") print(x)
print(myset) print(myset)
2. Using discard(): x = myset.pop()
myset = {'apple', 'banana','cherry'} print(x)
myset.discard("banana") print(myset)
print(myset)
7/21/2022 38
Python Data Type: Set

#Printing the Length of a Set in Python


myset = {'apple', 'banana','cherry'} # Set Operations
print(len(myset)) 1. Sets Union
Set_A = {1,2,3,4,5}
# Emptying a Python Set Completely Set_B = {4,5,6,7}
1. Using .clear() print(Set_A | Set_B)
myset = {'apple', 'banana','cherry'} 2. Sets Intersection
myset.clear() Set_A = {1,2,3,4,5}
print(myset) Set_B = {4,5,6,7}
2. Using del() print (Set_A & Set_B)
myset = {'apple', 'banana','cherry'} 3. Set difference
print(myset) Set_A = {1,2,3,4,5}
del myset Set_B = {4,5,6,7}
print(myset) print (Set_A - Set_B)
print (Set_B - Set_A)

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

You might also like