Unit 1
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually classes and
variables are instances (object) of these classes. The following are the standard or built-in
data types in Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
• Binary Types( memoryview, bytearray, bytes)
What is Python type() Function?
To define the values of various data types and check their data types we use the type()
function.
Examples:1
# DataType Output: str
x = "Hello Christist"
print(type(x))
# DataType Output: int
x = 50
print(type(x))
# DataType Output: float
x = 60.5
print(type(x))
# DataType Output: complex
x = 3j
print(type(x))
# DataType Output: list
x = ["Christ", "Deemed to be", "University"]
print(type(x))
# DataType Output: tuple
x = ("Christ", "Deemed to be", "University")
print(type(x))
# DataType Output: range
x = range(10)
print(type(x))
# DataType Output: dict
x = {"name": "Suraj", "age": 24}
print(type(x))
# DataType Output: set
x = {"Christ", "Deemed to be", "University"}
print(type(x))
# DataType Output: frozenset
x = frozenset({"Christ", "Deemed to be", "University"})
print(type(x))
# DataType Output: bool
x = True
print(type(x))
# DataType Output: bytes
x = b"Christ"
print(type(x))
# DataType Output: bytearray
x = bytearray(4)
print(type(x))
# DataType Output: memoryview
x = memoryview(bytes(6))
print(type(x))
# DataType Output: NoneType
x = None
print(type(x))
Output:
class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
<class 'NoneType'>
[Link] Data Type in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined
as Python int, Python float, and Python complex classes in Python.
• Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an
integer value can be.
• Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.
• Complex Numbers – Complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Example 2:
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Data Type in Python
The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python –
• Python String
• Python List
• Python Tuple
• String Data Type
--Strings in Python are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote, or triple-quote.
--In python there is no character data type, a character is a string of length one. It is
represented by str class.
Example3:Creating String
--Strings in Python can be created using single quotes or double quotes or even triple quote.
#Python Program for Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Christ World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Christist"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Chritist and I live in a world of "Christ University"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Christ
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Christ World
String with the use of Double Quotes:
I'm a Christist
<class 'str'>
String with the use of Triple Quotes:
I'm a Christist and I live in a world of "Christ University"
<class 'str'>
Creating a multiline String:
Christ
For
Life
• LifAccessing elements of String
--In Python, individual characters of a String can be accessed by using the method of
Indexing.
--Negative Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
Example3.1: Accessing elements of String
#Python Program to Access characters of String
String1 = "Christ Deemed to be University"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
Christ Deemed to be University
First character of String is:
C
Last character of String is:
y
• Reversing a Python String
With Accessing Characters from a string, we can also reverse them. We can Reverse a string
by writing [::-1] and the string will be reversed.
Example :Program to reverse a string
CME= "christ"
print(CME[::-1])
Output:
tsirhc
We can also reverse a string by using built-in join and reversed function.
Example # Program to reverse a string
x = "Christ for CME"
# Reverse the string using reversed and join function
x = "".join(reversed(x))
print(x)
Output:
EMC rof tsirhC
• String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String
is done by using a Slicing operator (colon).
# Example Python Program to demonstrate String slicing
# Creating a String
String1 = "Christ for CME"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Output:
Initial String:
Christ for CME
Slicing characters from 3-12:
ist for C
Slicing characters between 3rd and 2nd last character:
ist for C
• Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will cause
an error because item assignment or item deletion from a String is not supported. Although
deletion of the entire String is possible with the use of a built-in del keyword. This is because
Strings are immutable, hence elements of a String cannot be changed once it has been
assigned. Only new strings can be reassigned to the same name.
# Example:Python Program to Update character of a String
String1 = "Hello, I'm a student"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Output:
Initial String:
Christ for CME
Slicing characters from 3-12:
ist for C
Slicing characters between 3rd and 2nd last character:
ist for C
Initial String:
Hello, I'm a student
Updating character at 2nd Index:
Heplo, I'm a student
Heplo, I'm a student
Updating Entire String:
# Python Program to Update entire String
String1 = "Hello, I'm a student"
print("Initial String: ")
print(String1)
# Updating a String
String1 = "Welcome to the Christ World"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a student
Updated String:
Welcome to the Christ World
• Python has a set of built-in methods that you can use on
strings.
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the
position of where it was found
isalnum() Returns True if all characters in the string are
alphanumeric
isalpha() Returns True if all characters in the string are in the
alphabet
isascii() Returns True if all characters in the string are ascii
characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with
a specified value
rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a
list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
• List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.
Example 4: Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Creating a List
List = []
print("Initial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['Christ Deemed to be University']
print("\nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Christ", "Deemed","to be", "University"]
print("\nList containing multiple values: ")
print(List[0])
print(List[1])
print(List[2])
print(List[3])
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Christ', 'University'], ['Deemed to be']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List with the use of String:
['Christ Deemed to be University']
List containing multiple values:
Christ
Deemed
to be
University
Multi-Dimensional List:
[['Christ', 'University'], ['Deemed to be']]
Python Access List Items
• In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list.
• In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just
write List[-3].
• Negative indexing means beginning from the end, -1 refers to the last item, -2 refers
to the second-last item, etc
Example 4.1 Access list
# Python program to demonstrate accessing of element from list
# Creating a List with the use of multiple values
List = ["Christ", "Deemed to be", "University"]
# accessing a element from the list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output:
Accessing element from the list
Christ
University
Accessing element using negative indexing
University
Christ
List operations
I will do a grouping of the list operations according to the impact on these, my goal is making
easier the explanation and understanding:
1. Definition operations
These operations allow us to define or create a list.
1.1. [ ]
Creates an empty list.
y = []
2. Mutable operations
These operations allow us to work with lists, but altering or modifying their previous
definition.
2.1. append
Adds a single item to the bottom of the list.
x = [1, 2]
[Link]('h')
print(x)
Output:[1, 2, 'h']
2.2. extend
Adds another list to the end of a list.
x = [1, 2]
[Link]([3, 4])
print(x)
Output:[1, 2, 3, 4]
2.3. insert
Inserts a new element at a specific position in the list, this method receives the position as a
first argument, and the element to add as a second argument .
x = [1,2,3,4,5]
[Link](3, 'y')
print(x)
Output: [1, 2, 3, 'y', 4, 5]
2.4. del
Deletes the element located in the specific index. This method also has the possibility to
remove a section of elements from the list, through the “:” operator. You only need to define a
starting and end point [start:end], and note that the end point will not be considered. These
points can be ignored, whereby the 0 th position will be the starting point, and the last position
in the list will be the end point.
x = [1, 2, 3]
del x[1]
print(x)
Output:[1, 3]
y = [1, 2, 3, 4, 5]
del y[:2]
print(y)
Output:[3, 4, 5]
2.5. remove
Removes the first match for the specified item.
x = [1, 2, 'h', 3, 'h']
[Link]('h')
print(x)
Output:[1, 2, 3, 'h']
2.6. reverse
Reverses the order of the elements in the list, this places the final elements at the beginning,
and the initial elements at the end.
x = [1, 2, 'h', 3, 'h']
[Link]()
print(x)
Output:['h', 3, 'h', 2, 1]
2.7. sort
By default, this method sorts the elements of the list from smallest to largest, this behavior can
be modified using the parameter reverse = True.
x = [3, 2, 1, 4]
[Link]()
print(x)
Output: [1, 2, 3, 4]
It is important to know that when you apply the sort method, you must do it on lists that have
elements of the same data type, otherwise, you will face the TypeError exception.