Table of Contents
Add Your Heading Text Here
DATA TYPES
A Data type indicates which type of value a variable has in a program. However a python variables can store data of any data type but it is necessary to identify the different types of data they contain to avoid errors during execution of program. The most common data types used in python are str(string), int(integer) and float (floating-point).
1. Numeric
- Numeric data type means the data will have numeric value.
- Numeric value can be integer, floating number or even complex numbers.
a. Integers –
Int class is used to represent integers which may be a positive whole number or negative whole number. There is on restriction on limit for the value of integer. Integers are whole number values such as 50, 100,-3
b. Float –
Float class is used to represent floating point number which is a a real number with floating point representation. It is specified by a decimal point. Float is a value that use decimal point and therefore may have fractional point E.g.: 3.415, -5.15
c. Complex Numbers –
Complex class is used to represent Complex number specified as (real part) + (imaginary part)j. For example: 5 + 7j where 5 is the real part and 7 is the imaginary part.
By default when a user gives input it will be stored as string. But strings cannot be used for performing arithmetic operations. For example while attempting to perform arithmetic operation add on string values it just concatenates (joins together) the values together rather performing addition. For example : ‘25’ + ‘20’ = ‘45’ (As in the below Example)
PROGRAM:
# Python program to demonstrate numeric value
a = 10
print(“Type of a: “, type(a))
b = 20.0
print(“\nType of b: “, type(b))
c = 5 + 7j
print(“\nType of c: “, type(c))
Output:
Type of a: <class ‘int’>
Type of b: <class ‘float’>
Type of c: <class ‘complex’>
2. Boolean
The Boolean data type has two built-in values True or False. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans value. otherwise python will throw an error.
PROGRAM:
# Python program to demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class ‘bool’>
<class ‘bool’>
Traceback (most recent call last):
File “/home/vikash/boolean.py”, line 9, in
print(type(true))
NameError: name ‘true’ is not defined
3. Sequence Type
A sequence is an ordered collection of similar or different data items. Using sequence, Multiple values can be stored in the data type in an efficient manner. There are different types of sequence data type such as
i) Strings
ii) List
iii) Tuple
iv) Set
v) Dictionary
i) String
String is an array of bytes. Each byte represents a Unicode character. 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.
Individual characters of a String can be accessed by using the method of Indexing. 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. Only Integers are allowed to be passed as an index, float or other types will cause a TypeError.
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. 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.
Strings: Sequence of characters inside single quotes or double quotes.
E.g. w = “freeallnotes!..”
PROGRAM:
# Python Program for String Manipulation
# Creating a String with single Quotes, double quotes, tripple quotes
String1 = ‘Free’
String2 = “All”
String3 = ”’Notes”’
# Triple Quotes allows multiple lines
String4 = ”’Welcome
To
Freeallnotes”’
print(“\nUsing Single quote”)
print(String1)
print(“\nUsing Double quote”)
print(String2)
print(“\nUsing Triple quote”)
print(String3)
print(“\nUsing Triple quote to print multiline”)
print(String4)
#printing first character
print(“\nPringint First Character”)
print(String1[0])
#printing last character
print(“\nPringint Last Character”)
print(String1[-1])
#updating a single character
#String1[2] = ‘p’
#Cannot Update because strings are immutable
# Deleting a character of the String
#del String1[2]
#Cannot Delete because strings are immutable
# Escaping Single Quote
String1 = ‘I\’m “Trying”‘
print(“\nEscaping Single Quote: “)
print(String1)
# Escaping Doule Quotes
String1 = “I’m a \”Trying\””
print(“\nEscaping Double Quotes: “)
print(String1)
# Printing Paths with the
# use of Escape Sequences
String1 = “C:\\Python\\programs\\”
print(“\nEscaping Backslashes: “)
print(String1)
Output:
Using Single quote
Free
Using Double quote
All
Using Triple quote
Notes
Using Triple quote to print multiline
Welcome
To
Freeallnotes
Pringint First Character
F
Pringint Last Character
e
Escaping Single Quote:
I’m “Trying”
Escaping Double Quotes:
I’m a “Trying”
Escaping Backslashes:
C:\Python\programs\
>>>
ii) List
The List is an ordered sequence of data items. It is one of the flexible and very frequently used data type in Python. All the items in a list are not necessary to be of the same data type.
Declaring a list is straight forward methods. Items in the list are just separated by commas and enclosed within brackets [ ].
>>> list1 =[3.141, 100, ‘CSE’, ‘ECE’, ‘IT’, ‘EEE’]
Methods used in list
list1.append(x) | To add item x to the end of the list “list1” |
list1.reverse() | Reverse the order of the element in the list “list1” |
list1.sort() | To sort elements in the list |
list1.reverse() | To reverse the order of the elements in list1. |
Lists are similar to arrays but they are homogeneous always which makes it the most powerful tool in Python. A single list may contain Data Types like Integers, Strings, as well as Objects. Lists are mutable. Hence, they cannot be modified once created. Lists are ordered and have definite count. The list index starts with 0. Duplication of elements is possible in list. The lists are implemented by list class.
Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, list doesn’t need a built-in function for creation of list.
PROGRAM:
# Python program to demonstrate List
List = []
print(“Intial blank List: “)
print(List)
# Creating a List with the use of a String
List = [‘Welcome To www.freeallnotes.com’]
print(“\nList with the use of String: “)
print(List)
# Creating a List with the use of multiple values
List = [“Welcome”, “To”, “www.freeallnotes.com”]
print(“\nList containing multiple values: “)
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List (By Nesting a list inside a List)
List = [[‘Welcome’, ‘To’], [‘www.freeallnotes.com’]]
print(“\nMulti-Dimensional List: “)
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(“\nList after Addition of Three elements: “)
print(List)
# Addition of elements in a List
# Creating a List
List = []
print(“Initial blank List: “)
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(“\nList after Addition of Three elements: “)
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, ‘Notes’)
print(“\nList after performing Insert Operation: “)
print(List)
# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, ‘freeallnotes’, ‘Always’])
print(“\nList after performing Extend Operation: “)
print(List)
# Python program to demonstrate
# accessing of element from list
# Creating a List with
# the use of multiple values
List = [“Welcome”, “To”, “freeallnotes”]
# accessing a element from the
# list using index number
print(“\nAccessing element from the list”)
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print(“\nAccessing element using negative indexing”)
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print(“\nIntial List: “)
print(List)
# Removing elements from List
# using Remove() method
List.remove(3)
List.remove(4)
print(“\nList after Removal of two elements: “)
print(List)
List.pop()
print(“\nList after popping an element: “)
print(List)
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print(“\nList after popping a specific element: “)
print(List)
Output :
Intial blank List:
[]
List with the use of String:
[‘Welcome To www.freeallnotes.com’]
List containing multiple values:
Welcome
www.freeallnotes.com
Multi-Dimensional List:
[[‘Welcome’, ‘To’], [‘www.freeallnotes.com’]]
List after Addition of Three elements:
[[‘Welcome’, ‘To’], [‘www.freeallnotes.com’], 1, 2, 4]
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after performing Insert Operation:
[‘Notes’, 1, 2, 4, 12]
List after performing Extend Operation:
[‘Notes’, 1, 2, 4, 12, 8, ‘freeallnotes’, ‘Always’]
Accessing element from the list
Welcome
freeallnotes
Accessing element using negative indexing
freeallnotes
Welcome
Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 5, 6, 7, 8, 9, 10, 11, 12]
List after popping an element:
[1, 2, 5, 6, 7, 8, 9, 10, 11]
List after popping a specific element:
[1, 2, 6, 7, 8, 9, 10, 11]
>>>
iii) Tuple
Tuple is also an ordered sequence of items of different data types like list. But, in a list data can be modified even after creation of the list whereas Tuples are immutable and cannot be modified after creation. The advantages of tuples is to write-protect data and are usually very fast when compared to lists as a tuple cannot be changed dynamically.
The elements of the tuples are separated by commas and are enclosed inside open and closed brackets.
>>> t = (50,’python’, 2+3j)
List | Tuple |
>>> list1[12,45,27] >>> list1[1] = 55 >>> print(list1) >>> [12,55,27] | >>> t1 = (12,45,27) >>> t1[1] = 55 >>> Generates Error Message # Because Tuples are immutable |
The values stored in a tuple can be of any type, and they are indexed by integers. The important difference between a list and a tuple is that tuples are immutable. Tuples are hashable whereas lists are not. It is represented by tuple class.
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
PROGRAM:
# Python program to demonstrate Set
# Creating an empty tuple
Tuple1 = ()
print(“Initial empty Tuple: “)
print (Tuple1)
# Creating a Tuple with the use of Strings
Tuple1 = (‘Welcome’, ‘Sathyabama’)
print(“\nTuple with the use of String: “)
print(Tuple1)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print(“\nTuple using List: “)
print(tuple(list1))
# Creating a Tuple with the use of built-in function
Tuple1 = tuple(‘Sathyabama’)
print(“\nTuple with the use of function: “)
print(Tuple1)
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = (‘python’, ‘program’)
Tuple3 = (Tuple1, Tuple2)
print(“\nTuple with nested tuples: “)
print(Tuple3)
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print(“Frist element of tuple”)
print(tuple1[0])
# Accessing element from last
# negative indexing
print(“\nLast element of tuple”)
print(tuple1[-1])
print(“\nThird last element of tuple”)
print(tuple1[-3])
# demonstrate updation / deletion from a tuple
tuple1 = tuple([1, 2, 3, 4, 5])
print(“Initial tuple”)
print(tuple1)
# Updating an element of a tuple is not possible as it is immutable
#tuple1[0] = -1
# Deleting an element from a tuple is not possible as it is immutable
#del tuple1[2]
OUTPUT:
Initial empty Tuple:
()
Tuple with the use of String:
(‘Welcome’, ‘Sathyabama’)
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
(‘S’, ‘a’, ‘t’, ‘h’, ‘y’, ‘a’, ‘b’, ‘a’, ‘m’, ‘a’)
Tuple with nested tuples:
((0, 1, 2, 3), (‘python’, ‘program’))
Frist element of tuple
1
Last element of tuple
5
Third last element of tuple
3
Initial tuple
(1, 2, 3, 4, 5)
>>>
iv) Set
The Set is an unordered collection of unique data items.Items in a set are not ordered, separated by comma and enclosed inside { } braces. Sets are helpful inperforming operations like union and intersection. However, indexing is not done because sets are unordered.
List | Set |
>>> L1 = [1,20,25] >>> print(L1[1]) >>> 20 | >>> S1= {1,20,25,25} >>> print(S1) >>> {1,20,25} >>> print(S1[1]) >>> Error , Set object does not support indexing. |
It is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
PROGRAM:
# Python program to demonstrate Set in Python
set1 = set()
print(“Intial blank Set: “)
print(set1)
# Creating a Set with the use of a String
set1 = set(“Welcome to Python”)
print(“\nSet with the use of String: “)
print(set1)
# Creating a Set with the use of a List
set1 = set([“Python”, “is”, “Simple”])
print(“\nSet with the use of List: “)
print(set1)
# Creating a Set with a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, ‘Python’, 4, ‘is’, 6, ‘simple’])
print(“\nSet with the use of Mixed Values”)
print(set1)
# Addition of elements in a Set
set1 = set()
print(“Intial blank Set: “)
print(set1)
# Adding element and tuple to the Set
set1.add(8)
set1.add(9)
set1.add((6, 7))
print(“\nSet after Addition of Three elements: “)
print(set1)
# Addition of elements to the Set using Update function
set1.update([10, 11])
print(“\nSet after Addition of elements using Update: “)
print(set1)
# Accessing of elements in a set
# Creating a set
set1 = set([“Python”, “is”, “Excellent”])
print(“\nInitial set”)
print(set1)
# Accessing element using for loop
print(“\nElements of set: “)
for i in set1:
print(i, end =” “)
# Checking the element using in keyword
print(“Great” in set1)
# Deletion of elements in a Set
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print(“Intial Set: “)
print(set1)
# Removing elements from Set using Remove() method
set1.remove(5)
set1.remove(6)
print(“\nSet after Removal of two elements: “)
print(set1)
# Removing elements from Set using Discard() method
set1.discard(8)
set1.discard(9)
print(“\nSet after Discarding two elements: “)
print(set1)
# Removing element from the Set using the pop() method
set1.pop()
print(“\nSet after popping an element: “)
print(set1)
# Removing all the elements from Set using clear() method
set1.clear()
print(“\nSet after clearing all the elements: “)
print(set1)
OUTPUT:
Intial blank Set:
set()
Set with the use of String:
{‘t’, ‘ ‘, ‘h’, ‘o’, ‘e’, ‘m’, ‘W’, ‘P’, ‘c’, ‘y’, ‘n’, ‘l’}
Set with the use of List:
{‘Python’, ‘is’, ‘Simple’}
Set with the use of Mixed Values
{1, 2, 4, 6, ‘is’, ‘Python’, ‘simple’}
Intial blank Set:
set()
Set after Addition of Three elements:
{8, 9, (6, 7)}
Set after Addition of elements using Update:
{8, 9, (6, 7), 10, 11}
Initial set
{‘Python’, ‘is’, ‘Excellent’}
Elements of set:
Python is Excellent False
Intial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set after Removal of two elements:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
Set after Discarding two elements:
{1, 2, 3, 4, 7, 10, 11, 12}
Set after popping an element:
{2, 3, 4, 7, 10, 11, 12}
Set after clearing all the elements:
set()
>>>
4. Dictionary
Dictionary is an unordered collection of data values. It is used to store data values like a map. Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair is separated by a colon :, whereas each key is separated by a ‘comma’.
Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Dictionaries are optimized for retrieving data when there is huge volume of data. They provide the key to retrieve the value.
>>> d1={1:’value’,’key’:2}
>>> type(d)
PROGRAM:
# Creating an empty Dictionary
Dict = {}
print(“Empty Dictionary: “)
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: ‘Python’, 2: ‘Is’, 3: ‘Powerful’}
print(“\nDictionary with the use of Integer Keys: “)
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {‘Name’: ‘Python’, 1: [1, 2, 3, 4]}
print(“\nDictionary with the use of Mixed Keys: “)
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘Python’, 2: ‘Is’, 3:’Efficient’})
print(“\nDictionary with the use of dict(): “)
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, ‘Python’), (2, ‘Programming’)])
print(“\nDictionary with each item as a pair: “)
print(Dict)
# Creating an empty Dictionary
Dict = {}
print(“Empty Dictionary: “)
print(Dict)
# Adding elements one at a time
Dict[0] = ‘Python’
Dict[2] = ‘Program’
Dict[3] = 1
print(“\nDictionary after adding 3 elements: “)
print(Dict)
# Updating existing Key’s Value
Dict[2] = ‘Welcome’
print(“\nUpdated key value: “)
print(Dict)
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: ‘Python’, ‘name’: ‘Is’, 3: ‘Case-Sensitive’}
# accessing a element using key
print(“Accessing a element using key:”)
print(Dict[‘name’])
# accessing a element using get() method
print(“Accessing a element using get:”)
print(Dict.get(3))
# Initial Dictionary
Dict = { 5 : ‘Welcome’, 6 : ‘To’, 7 : ‘Python’,
‘A’ : {1 : ‘Python’, 2 : ‘Is’, 3 : ‘Simple’},
‘B’ : {1 : ‘Python’, 2 : ‘Pramming’}}
print(“Initial Dictionary: “)
print(Dict)
# Deleting a Key value
del Dict[6]
print(“\nDeleting a specific key: “)
print(Dict)
# Deleting a Key
# using pop()
Dict.pop(5)
print(“\nPopping specific element: “)
print(Dict)
# Deleting an arbitrary Key-value pair using popitem()
Dict.popitem()
print(“\nPops an arbitrary key-value pair: “)
print(Dict)
# Deleting entire Dictionary
Dict.clear()
print(“\nDeleting Entire Dictionary: “)
print(Dict)
OUTPUT:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: ‘Python’, 2: ‘Is’, 3: ‘Powerful’}
Dictionary with the use of Mixed Keys:
{‘Name’: ‘Python’, 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: ‘Python’, 2: ‘Is’, 3: ‘Efficient’}
Dictionary with each item as a pair:
{1: ‘Python’, 2: ‘Programming’}
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: ‘Python’, 2: ‘Program’, 3: 1}
Updated key value:
{0: ‘Python’, 2: ‘Welcome’, 3: 1}
Accessing a element using key:
Is
Accessing a element using get:
Case-Sensitive
Initial Dictionary:
{5: ‘Welcome’, 6: ‘To’, 7: ‘Python’, ‘A’: {1: ‘Python’, 2: ‘Is’, 3: ‘Simple’}, ‘B’: {1: ‘Python’, 2: ‘Pramming’}}
Deleting a specific key:
{5: ‘Welcome’, 7: ‘Python’, ‘A’: {1: ‘Python’, 2: ‘Is’, 3: ‘Simple’}, ‘B’: {1: ‘Python’, 2: ‘Pramming’}}
Popping specific element:
{7: ‘Python’, ‘A’: {1: ‘Python’, 2: ‘Is’, 3: ‘Simple’}, ‘B’: {1: ‘Python’, 2: ‘Pramming’}}
Pops an arbitrary key-value pair:
{7: ‘Python’, ‘A’: {1: ‘Python’, 2: ‘Is’, 3: ‘Simple’}}
Deleting Entire Dictionary:
{}
>>>
You May Like to Browers More


