Python Data Types With Examples

Standard data types

Data type represents the kind of value and what operation can be performed on that value. A variable can hold different types of values. For example a person age can be stored in numeric value, e.g. Age=65, and his name should be stored in string data type.

Below are the some standard data-types provided by Python

String Type (str)

String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ”’ or “””.
EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    emp_Name = "James"  #this is single line string
    emp_Address = '''DLF Cyber City,
    Sector-25A, Phase-III,
    Gurgaon - 122002
    '''                 #this is multi-line string
    
    print("Employee Name : " + emp_Name)
    print("Employee Address : " + emp_Address)
        
if __name__ == "__main__":
    main() 

OUTPUT:

Employee Name : James
Employee Address : DLF Cyber City,
    Sector-25A, Phase-III,
    Gurgaon - 122002

Go to top ( Standard data types )


Numbers Type (int, float, complex)

It is used to store the numeric value. The integer, float, and complex values belong to a Python Numbers data-type.
We will use the type() function to know the data-type of variable.
EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    first_Number = 10 #interger type
    second_Number = 15.5 # float tpue
    third_Number  = 5 + 5j # Complex type
    
    print("Type of first_Number is " + str(type(first_Number)))
    print("Type of second_Number is " + str(type(second_Number)))
    print("Type of third_Number is " + str(type(third_Number)))
    
if __name__ == "__main__":
    main() 

OUTPUT:

Type of first_Number is <class 'int'>
Type of second_Number is <class 'float'>
Type of third_Number is <class 'complex'>

Go to top ( Standard data types )


Sequence Type (list, tuple, range)

List is an ordered sequence of items. Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and enclosed within square brackets [].

Tuple is an ordered sequence of items same as a list. Both List and Tuple are similar in many ways. The only difference is that tuples are immutable i.e. Tuples once created cannot be modified. It is defined within parentheses () where items are separated by commas.

Range use to generates a sequence of integers by defining a start and the end point of the range.

EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    #list, tuple, range
    var_list1 = [11, 12.5] #list type]
    var_list2 = [13.7, 14, 15, "string"] #list type
                 
    var_tuple = (21, 22, 23.9, 24, "str") #tuple tpue
    var_range  = range(1,10) # range type
    
    print("Type of var_list is " + str(type(var_list1)))
    print("Type of var_tuple is " + str(type(var_tuple)))
    print("Type of var_range is " + str(type(var_range)))
    print("\n")
    print("LIST:")
    print(var_list1)
    print(var_list2)
    print(var_list1 + var_list2)
    
    var_list1.append("str_appended")
    print(var_list1)
    print("\n")
    print("TUPLE:")
    print(var_tuple)
    '''
    in below line we are trying to modify the immutable tuples
    it will give us error
    '''
    #var_tuple.append("str_appended") #
    print("\n")
    print("RANGE:")
    for i in var_range:
        print(i)
    
if __name__ == "__main__":
    main() 
    

OUTPUT:

Type of var_list is <class 'list'>
Type of var_tuple is <class 'tuple'>
Type of var_range is <class 'range'>


LIST:
[11, 12.5]
[13.7, 14, 15, 'string']
[11, 12.5, 13.7, 14, 15, 'string']
[11, 12.5, 'str_appended']


TUPLE:
(21, 22, 23.9, 24, 'str')


RANGE:
1
2
3
4
5
6
7
8
9

Go to top ( Standard data types )


Boolean Type (bool)

Boolean data-types is used for TRUE and FALSE value. True is represented by any non-zero value or ‘T’ whereas false is represented by the 0 or ‘F’.

EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    num1 = 10
    num2 = 15
    bool_isGreater = True
    
    if (num1 > num2):
        bool_isGreater = True
    else:
        bool_isGreater = False
   
    print("Is num1 greater than num2 : " + str(bool_isGreater))
    
    print("Type of bool_isGreater is " + str(type(bool_isGreater)))
    
if __name__ == "__main__":
    main() 
    

OUTPUT:

Is num1 greater than num2 : False
Type of bool_isGreater is <class 'bool'>

Go to top ( Standard data types )


Set Type (set, frozenset)

Set is mutable, an unordered collection of unique items. A set object is used to perform mathematical set operations like union, intersection, difference, etc.

frozenset: Frozenset is immutable version of set whose elements are added from iterable. It takes an iterable object as input and makes them immutable.

EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    set_group1 = {'prem', 'anshuman', 'james'}
    set_group2 = {'prem', 'james', 'radha'}
    
    print("Type of set_group1 is " + str(type(set_group1)))
    print("Type of set_group2 is " + str(type(set_group2)))
    
    print("\n")
    set_union = set_group1.union(set_group2)
    print("Below is Union of Both set_group1 & set_group2, All items are unique")
    print(set_union)
    
    print("\n")
    set_intersection = set_group1.intersection(set_group2)
    print("Below is intersection of Both set_group1 & set_group2")
    print(set_intersection)
    
    print("\n")
    set_difference = set_group1.difference(set_group2)
    print("Below is set_difference of Both set_group1 & set_group2")
    print(set_difference)
    
    print("\n")
    print("frozenset Example")
    list_favourite_fruits = ["mango", "apple", "banana"] #List of favourite fruits
    frozenset_favourite_fruits = frozenset(list_favourite_fruits) #Passing iterable(List) 
    print("Below is frozenset_favourite_fruits ")
    print(frozenset_favourite_fruits)
    
    print("Trying to update the frozenset object this will give use error")
    frozenset_favourite_fruits[1] = "guava"
    
if __name__ == "__main__":
    main() 
    

OUTPUT:

Type of set_group1 is <class 'set'>
Type of set_group2 is <class 'set'>


Below is Union of Both set_group1 & set_group2, All items are unique
{'prem', 'anshuman', 'james', 'radha'}


Below is intersection of Both set_group1 & set_group2
{'prem', 'james'}


Below is set_difference of Both set_group1 & set_group2
{'anshuman'}


frozenset Example
Below is frozenset_favourite_fruits 
frozenset({'mango', 'banana', 'apple'})
Trying to update the frozenset object this will give use error
Traceback (most recent call last):
TypeError: 'frozenset' object does not support item assignment

Go to top ( Standard data types )


Dictionary Type(dict)

Dictionary is an unordered set of a key-value pair of items. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys. The Keys of dictionary can be any number or string, whereas cab be an arbitrary Python object.

EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    
    emp_dict = {"name":"prem" , "age":30, "country" : "India"}
    #byte_str = b"Hello, It is wonderful World !"
    print("Dictionary :-")
    print("Type of emp_dict is " + str(type(emp_dict)))
    print(emp_dict)
    
    print("\n")
    print("Below are all keys of dictionary object")
    print(emp_dict.keys)
    
    print("\n")
    print("Below are all values of dictionary object")
    print(emp_dict.values)
    
    print("\n")
    print("adding new item, key:value pair")
    emp_dict["tel"] = "9999999999"
    print(emp_dict)  
    
    print("\n")
    print("Check whether 'name' key-word exist or not : " + str(("name" in emp_dict)))
    print("Check whether 'address' key-word exist or not : " + str(("address" in emp_dict)))
    
if __name__ == "__main__":
    main() 
    

OUTPUT:

Dictionary :-
Type of emp_dict is <class 'dict'>
{'name': 'prem', 'age': 30, 'country': 'India'}


Below are all keys of dictionary object



Below are all values of dictionary object



adding new item, key:value pair
{'name': 'prem', 'age': 30, 'country': 'India', 'tel': '9999999999'}


Check whether 'name' key-word exist or not : True
Check whether 'address' key-word exist or not : False

Go to top ( Standard data types )


Binary Type(bytes, bytearray, memoryview)

bytes objects contain single bytes. It is immutable sequence of bytes. Bytes objects can be constructed using bytes(). It can also be constructed from literals. To constructed from literals use a b prefix with normal string.

bytearray objects also contain single bytes. It is mutable sequence of bytes. Bytearray objects can be constructed using bytearray() function.

memoryview objects contain byte-oriented data. It allow Python code to access the internal data of an object that supports the buffer protocol without copying. memoryview objects can be constructed using memoryview() function. The memoryview() function allows direct read and write access to an object’s byte-oriented data without needing to copy it first.

EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 22:31:40 2021
@author: mycloudplace
"""
def main():
    byte_str = b"Hello, It is wonderful World !"
    print("bytes :-")
    print("Type of byte_str is " + str(type(byte_str)))
    print(byte_str)
    print("\n")

    #creating by using the bytes() function
    str_hello = "This is sample sentence."
    print("bytes function :-")
    byte_str2 = bytes(str_hello, 'utf8')
    print("Type of byte_str2 is " + str(type(byte_str2)))
    print(byte_str2)
    print("\n")
    
    print("bytes array :-")
    byte_array = bytearray(str_hello, 'utf-8')
    print("Type of byte_array is " + str(type(byte_array)))
    print(byte_array)
    print("\n")
    
    print("memoryview :-")
    memory_view = memoryview(byte_array)
    print("Type of memory_view is " + str(type(memory_view)))
    print(memory_view)
    print("\n")

    # Updating 2nd and 3rd index of memory_view, 'This' will converted to 'That'  
    print('Before update:', byte_array)
    print("Updating 2nd and 3rd index of memory_view, 'This' will be converted to 'That' ")
    memory_view[2]= 97
    memory_view[3]= 116
    print('After update:', byte_array)
    
if __name__ == "__main__":
    main() 
    

OUTPUT:

bytes :-
Type of byte_str is <class 'bytes'>
b'Hello, It is wonderful World !'


bytes function :-
Type of byte_str2 is <class 'bytes'>
b'This is sample sentence.'


bytes array :-
Type of byte_array is <class 'bytearray'>
bytearray(b'This is sample sentence.')


memoryview :-
Type of memory_view is <class 'memoryview'>


Before update: bytearray(b'This is sample sentence.')
Updating 2nd and 3rd index of memory_view, 'This' will be converted to 'That' 
After update: bytearray(b'That is sample sentence.')

Go to top ( Standard data types )

Our Previous articles

Python – installation indentation variable comments

Python Programming Introduction

Python Office Site : https://docs.python.org/3/library/datatypes.html

18 thoughts on “Python Data Types With Examples”

  1. Pingback: Python Useful Build-in Functions With Examples | How to create a new function - Mycloudplace

  2. Pingback: Python array | numpy for python | How to create numpy or np array in python - Mycloudplace

  3. Pingback: File Handling Python With Examples | Python Input-Output Awesome Tips - Mycloudplace

Leave a Comment

Your email address will not be published. Required fields are marked *