As the name suggests, Python data types are nothing but defining the type of the variable.
Here in Python, we don’t need to declare a variable explicitly mentioning the data type. This feature in Python is known as dynamic typing.

We will also be discussing:

  • Python Date and Time

Datatypes in Python


In python, numbers are divided into five datatypes.
They are:

  • integer,
  • long integer,
  • octal and hexadecimal,
  • floating-point and
  • complex numbers


Python integers are nothing but whole numbers, whose range dependent on the hardware on which python is run.
Integers can be of different types such as positive, negative, zero, and long.

I = 123   #Positive Integer
J = -20  #Negative Integer
K = 0     #Zero Integer

Long Integers

L suffix is used for the representation of long integers in python. Long integers are is used to store large numbers without losing precision.

I = 99999999999L

Octal and Hexadecimal

In python, we also have another number datatype called octal and a hexadecimal number.

  • To represent the octal which has base 8 in python add a preceding 0 (zero), so that Python interpreter can recognize that you want the value to be in base 8 and not in base 10.
I = 11
#Then in Octal you will write –
I = 011
print (I)
Output 9
  • To represent the hexadecimal numbers (base 16) in Python, add a preceding 0x, so that the interpreter can recognize that you want the value to be in base 16 and not in base 10.
I = 0x11
print (I)
Output 17

Floating Point numbers

Floating point numbers symbolize the real numbers that are written with a decimal point dividing the integer and fractional parts.
Floating point numbers may also be in scientific notation with E or e, indicating the power of 10
5.6e2 that means 5.6 * 102.

I = 2.5
J = 7.5e4

Complex Numbers

Complex numbers are of the form of a + bj, where a is real part floating value and b is the imaginary part floating value and j represents the square root of -1.

2.5 + 2j

Now let us move ahead and discuss another very important and widely used python datatype which is called string


Python string is an ordered collection of characters which is used to represent and store the text-based information. Strings are stored as individual characters in a contiguous memory location. It can be accessed from both the directions in forward and backward.

Creating String:

Name = “Hello Intellipaat”

Accessing string characters:

It can be accessed from both the directions in forward and backward. Forward indexing start form 1,2,3… Whereas backward indexing start form -1, -2, -3….

Name = “Hello Intellipaat”
print (Name [1])
Output: eprint (Name [-1])
Output: t

Updating String:

Strings are immutable that means once a string binds to a variable it can’t be modified.

Strings Operators

There are 3 types of operators are supported by the string which are –

  • Basic Operators (+, *)
  • Relational Operators (<, ><=, >=, ==, !=)
  • Membership Operators (in, not in)

Table: Common String Constants and Operations

s1 = ‘  ’Empty string
s2 = “a string”Double quotes
block = ‘‘‘…’’’Triple-quoted blocks
s1 + s2Concatenate
s2 * 3repeat
“a %s parrot” % ‘dead’String formatting
for x in s2Iteration
‘m’ in s2membership

Table:  String Backslash Characters

\newlineIgnored (a continuation)
\nNewline (ASCII linefeed)
\\Backslash (keeps one \)
\vVertical tab
\’Single quote (keeps ‘)
\tHorizontal tab
\”Double quote (keeps “)
\rCarriage return
\aASCII bell
\fForm feed
\0XXOctal value XX
\eEscape (usually)
\xXXHex value XX
\000Null (doesn’t end string)

Example: Program to concatenate two strings

S1 = “hello”
S2 = “Intellipaat”
print (S1 + S2)

Built in string methods:

capitalize()It capitalizes the first letter of string
center(width, fillchar)It returns a space-padded string with the original string centered to a total of width columns.
count(str, beg= 0,end=len(string))It counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
encode(encoding=’UTF-8′,errors=’strict’)It returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
endswith(suffix, beg=0, end=len(string))It returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
endswith(suffix, beg=0, end=len(string))It determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8)It expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tab size not provided.
find(str, beg=0 end=len(string))It determines if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string))Works just like find(), but raises an exception if str not found.
isalnum()It returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isalpha()It returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
isdigit()It returns true if string contains only digits and false otherwise.
islower()It returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
isupper()It returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
len(string)It returns the length of the string
max(str)It returns the max alphabetical character from the string str.
min(str)It returns the min alphabetical character from the string str.
upper()It converts lowercase letters in a string to uppercase.
rstrip()It removes all trailing whitespace of string.
split(str=””, num=string.count(str))Splits string according to delimiter str (space if not provided any), returns list of substrings which are split into at most num substrings if given
splitlines( num=string.count(‘\n’))Splits string at the newlines and returns a list of each line with newlines removed.


Lists are Python’s most flexible ordered collection object type.  It can also be referred to as a sequence that is an ordered collection of objects that can host object of any type, numbers, letters, strings and nested lists as well.

Creating a list:

A list can be created by putting the value inside the square bracket and values are separated by a comma.

<list name>=[value1,value2,…,value n]

Unlike strings, lists can contain any sort of object: numbers, strings, even other lists. Python lists are:

  • Ordered collections of arbitrary objects
  • Accessed by offset
  • Arrays of object references
  • Variable length, heterogeneous, arbitrarily nestable
  • Of the category mutable sequence
  • The elements are stored in the index basis with starting index as 0.
  • A python list is enclosed between square( [ ] ) brackets.
list1 = [1,2,3,4,5]

Creating Multi-Dimensional Lists:

One dimensional:

init_list = [0]*3
[0, 0, 0]

Two-dimensional List:

two_dim_list = [ [0]*3 ] *3

Three dimensional:

two_dim_list = [ [0]*3 ] *3
print(two_dim_list)[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Conflict in multi-dimensional lists:

two_dim_list[0][2] = 1
[[0, 0, 1], [0, 0, 1], [0, 0, 1]]

List Comprehension

List Comprehension.” It helps in constructing lists in a completely natural and easy way.

List1 = [expression(iter) for iter in oldList if filter(iter)]
List1 = [ i for i in range(5)]
print(List1)[0, 1, 2, 3, 4]

Complicated list comprehension examples:


print ([a+b for a in ‘mug’ for b in ‘lid’])
[‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]


list_fruit = [“Apple”,”Mango”,”Banana”,”Avocado”]
first_letters = [ fruits[0] for fruits in list_fruit ]
print(first_letters)[‘A’, ‘M’, ‘B’, ‘A’]

Fixing multi-dimensional conflict using list comprehension:

two_dim = [[0]*3 for i in range(3)]
print(two_dim)[[0, 0, 0], [0, 0, 0], [0, 0, 0]]two_dim[0][2] = 1
[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

List Extension:

Python allows lists to resize in many ways. You can do that just by adding two or more of them.

two_dim = [[0]*3 for i in range(3)]print(two_dim)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
two_dim[0][2] = 1
[[0, 0, 1], [0, 0, 0], [0, 0, 0]]


Alternately you can do that by using extend() method:

L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
[‘a’, ‘b’, ‘c’, ‘d’]


Next, you can append a value to a list by calling the append() method. See the below example.

L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
[‘a’, ‘b’, ‘c’, ‘d’]

Accessing a list:

To access a list in python we use indexing.


For instance,

list1 = [1,2,3,4,5]

Accessing a list using Reverse indexing:


Slicing a Python List:

[3, 4]list1[2:-1]
[3, 4]list1[:2]
[1, 2]

Other common list operations:

Iterate a list

for element in list1:

Update/ add

list1[4] = ‘number’print(list1)
[1, 2, 3, 4, ‘number’]
list1[4:7] = [“Apple”,”Mango”,”Banana”]
[1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]
[33, 1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]
[33, 1, 2, 3, 4, ‘Apple’, 29, ‘Mango’, ‘Banana’]

Remove/Delete elements:

list1 = [1,2,3,4,5]del list1[2]
[1, 2, 4, 5]

list1 = [1,2,3,4,5]
[1, 2, 3, 5]
list1 = [1,2,3,4,5]
[1, 3, 4, 5]

Sorting list:

Python list implements the sort() method for ordering (in both ascending and descending order) its elements in place.


Sort in ascending order:

list1 = [1,3,2,4,5,9,6]
[1, 2, 3, 4, 5, 6, 9]

Sort in descending order:

list1 = [1,3,2,4,5,9,6]
[9, 6, 5, 4, 3, 2, 1]

Python list methods and functions:

min(list_name)Returns the minimum value from the list
max(list_name)Returns the largest value from the list.
len(list_name)Returns number of elements in a list.
cmp(list1,list2)Compares the two lists.
list.reverse()Reverse the list
list.sortSort the list
list(sequence)Convert the sequence into the list
list.append(value)Add the value into the list
list.remove(value)Remove the value from the list


Tuple is a collection type immutable data structure that holds a sequence of heterogeneous elements. Now, what does immutable data structure mean here? It means that tuple don’t allow you to modify its elements.

Creating tuple:

# create an empty tuple
tuple1 = ()
print(“A blank tuple:”, tuple1)
# create a tuple without using round brackets
tuple1 = 33, 55, 77
print(“A tuple set without parenthesis:”, tuple1, “type:”, type(tuple1)) 
A tuple set without parenthesis: (33, 55, 77) type: <class ‘tuple’>
# create a tuple of numbers
tuple1 = (3, 6, 9)
print(“A tuple of numbers:”, tuple1)output:
A tuple of numbers: (3, 6, 9)
# create a tuple of mixed data types
tuple1 = (5, “5”, [5, 9])
print(“A tuple of mixed data types:”, tuple1)output:
A tuple of mixed data types: (5, ‘5’, [5, 9])
# create a tuple of tuples
# i.e. a nested tuple
tuple1 = ((‘a’, ‘b’, ‘c’), (‘X’, ‘Y’, ‘Z’))
print(“A tuple of tuples:”, tuple1)output:
A tuple of tuples: ((‘a’, ‘b’, ‘c’), (‘X’, ‘Y’, ‘Z’))

Accessing tuple:

Via indexing

tuple1 = (1,2,3,4,5,6)
print(“The tuple:”, tuple1, “Length:”, len(tuple1))
# Indexing the first element
print(“tuple1[0]:”, tuple1[0])
The tuple: (1, 2, 3, 4, 5, 6) Length: 6
tuple1[0]: 1

Via reverse indexing

tuple1 = (1,2,3,4,5,6)

Via slicing operator

(2, 3, 4, 5, 6)
(2, 3, 4, 5)

Performing operations in tuple

Modifying tuple

Tuples in python are immutable.

Deleting tuple

Tuples in python are immutable.


A set is a collection that stores elements of different data types. Remember that, set doesn’t index them in a particular order. Let us look at some of the properties of set in python.

  • In the set, elements don’t have a specific order.
  • Set can’t have duplicates. Each item is unique.
  • Set elements are immutable. They can’t accept changes once added.
  • But the set is mutable. Set allows addition and deletion operations.

Instantiate A Set:

  • Using comma to separate and curly braces to group elements
myset = {“apple”, “banana”, “cherry”}
  • Set():
myset = set((“apple”, “banana”, “cherry”)) # note the double round-bracketsprint(myset)

Remember that once a set is created you can change that you can only add elements. Now let us see how to add items in a python set

Set Operations:

Add items

Using add():

myset = {“apple”, “banana”, “cherry”}

Using update():

myset = {“apple”, “banana”, “cherry”}
myset.update([“orange”, “mango”, “grapes”])

Length of a Set:

myset = {“apple”, “banana”, “cherry”}

Remove items:

Remove operation can be performed by using
Using remove():

myset = {“apple”, “banana”, “cherry”}

Note: If the item to be removed does not exist, remove() will raise an error
Using discard():

myset = {“apple”, “banana”, “cherry”}

Note: If the item to be removed does not exist, discard() will not raise an error.
Using pop():
Remember that pop() will remove the last item of the set. Since set is unordered, we should avoid performing pop() in set.

myset = {“apple”, “banana”, “cherry”}
x = myset.pop()

Empty a set completely:

To clear a set completely we can use either clear() method or del() method.
Using clear():

myset = {“apple”, “banana”, “cherry”}

Using del():

myset = {“apple”, “banana”, “cherry”}
del myset

Common set methods:

update()It updates the set with the union of this set and others
add()It adds an element to the set
clear()It removes all the elements from the set
copy()It returns a copy of the set
difference()It returns a set containing the difference between two or more sets
difference_update()It removes the items in this set that are also included in another, specified set
discard()It removes the specified item
remove()It removes the specified element
pop()It removes an element from the set
intersection()It returns a set, that is the intersection of two other sets
intersection_update()It removes the items in this set that are not present in other, specified set(s)
isdisjoint()It returns whether two sets have a intersection or not
issubset()It returns whether another set contains this set or not
issuperset()It returns whether this set contains another set or not
symmetric_difference()It returns a set with the symmetric differences of two sets
symmetric_difference()It returns a set with the symmetric differences of two sets
union() or |It returns a set containing the union of sets
intersection or & It returns a set comprising common elements in both the sets

Now that we are familiar with the set and its operations, we will be discussing another very important datatype which is nothing but a dictionary.


Dictionary in Python is a collection of objects where we have a value field and a key field. A dictionary in python stores a key along with its values that are defined in the following manner:

Example_dict ={‘fruit’ : ‘apple’, ‘color’ : ‘green’}

Now that we got to know what dictionary is, let us go ahead and create the dictionary and perform a few important operations on that.

Create a dictionary:

We can create a dictionary using the following methods:

  • General method:
My_dict = {‘fruit’: ‘apple’, ‘color’ : ‘green’, ‘quality’ : ‘checked’}
  • Using dict():
My_dict = dict(fruit=‘apple’, color=‘green’, ‘quality’: ‘checked’)

Now that we have created a dictionary to let us see how to access some items in that dictionary:

Access items in a dictionary:

Using key:

Access the items of a dictionary by referring to its key name

My_dict [‘fruit’]

Using get():

x = My_dict.get(‘fruit’)

Common dictionary methods:

Change values:


Loop through a dictionary:

Let us say we want to print all the values of a dictionary.

for x in My_dict:

Adding items:

My_dict[‘weight’] =10

Removing items from a dictionary:

Using pop():
To remove the item with the specified key name


Using del():
To remove the item with the specified key name


Removing the complete dictionary:

del My_dict

Using clear():
clear() empties the dictionary


Dictionary length:


Check all the keys:


Check all the values:


Common dictionary methods:

clear()It removes all the elements from the dictionary
copy()It returns a copy of the dictionary
fromkeys()It returns a dictionary with the specified keys and values
get()It returns the value of the 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 the element with the specified key
popitem()It removes the last inserted (key, value) pair
setdefault()It returns the value of the specified key.
update()It updates the dictionary with the specified key-value pairs
values()It returns a list of all the values in the dictionary

After dictionary, another datatype that we have in python is Boolean Datatype. Let us see how Boolean works in python.


A Boolean is such a data type that can have two values – True or False. These values can be used to assign or compare Boolean values.

str = “Hello World”#len(str)=11
len(str) == 11 
len(str) != 11

Now that we have got to know about the python datatypes we will be discussing about the type conversion methods that we use in python.

Type Conversion:

This is nothing but the process of converting the value of one data type to another data type.
Python has two types of type conversion.

  • Implicit Type Conversion
  • Explicit Type Conversion

Implicit Type Conversion:

Python Implicit Type Conversion
In this case, Python automatically converts one datatype to another datatype without any involvement.
Example 1: Let us see how type conversion happen implicitly from integer to float

number_int = 23number_float = 1.25
number_new = number_int + number_float
print(“Datatype of numbr_int:”,type(number_int))
print(“Datatype of number_float:”,type(number_float))
print(“Value of number_new:”,number_new)
print(“Datatype of number_new:”,type(number_new))
datatype of number_int: <class ‘int’>
datatype of number_float: <class ‘float’>
Value of number_new: 24.25
datatype of number_new: <class ‘float’>

We can see how python allows us to add integer and float numbers that results in a float number.
Now, let’s try another similar example with a string, which is a higher data type and an integer, which is a lower datatype.
Example 2: Addition of string and integer datatype

number_int = 123number_string = “123”
print(“Data type of number_int:”,type(number_int))
print(“Data type of number_string:”,type(number_string))
Data type of number_int: <class ‘int’>
Data type of number_string: <class ‘str’>

Traceback (most recent call last):
File “python”, line 6, in <module>
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

We tried to add integer and string and we got a type error.
Even though Python is unable to use Implicit Conversion conditions like this, Python also has a solution for such situations which is Explicit Conversion.

Explicit Type Conversion:

Python Explicit Type Conversion
In this case, users involvement is required. Users convert the datatype of an object to required datatype.
How to perform explicit type conversion?  Answer is, with the help of some predefined functions like int(), float(), str(), etc. Type conversion is also known as typecasting because the user casts or makes a change in the data type.
Syntax :


Let us understand with the help of the last example from the implicit type conversion method.
Example 3: Addition of string and integer using explicit conversion

number_int = 123number_string = “123”
print(“Data type of number_int:”,type(number_int))
print(“Data type of number_string before Type Casting:”,type(number_string))
number_string = int(number_string)
print(“Data type of number_string after Type Casting:”,type(number_string))
number_sum = number_int + number_string
print(“Sum of number_int and number_string:”,number_sum)
print(“Data type of the sum:”,type(number_sum))
Data type of number_int: <class ‘int’>
Data type of number_string before Type Casting: <class ‘str’>

Data type of number_string after Type Casting: <class ‘int’>
Sum of number_int and number_str: 579
Data type of the sum: <class ‘int’>

Note: In Typecasting loss of data may occur as we enforce the object to specific data type.
Let us see some other type conversion methods that might come in handy while dealing with real-world projects.

int(a, 2)Converting integer to base 2( here, a is an integer)
float()Converting datatype to floating point number
ord()Converting character to integer
hex()Convert integer to hexadecimal string
oct()Convert integer to octal string
tuple()Converting to a tuple
set()Converting string to set
list() Converting any data type to a list type
dict() Converting a tuple of order (key, value) into a dictionary
str() Converting integer into a string
complex(real,imag) Converts real numbers to complex(real,imag) number.

Python Date and Time:

It is used to retrieve current date and time. localtime() function is used to retrieve the current time and take time.time() parameter where time() is a function which returns the current system time in number of ticks since epoch (12 January 1970). Tick is basically a floating point number in seconds since epoch.

import time;
localtime = time.localtime(time.time())
print  localtime
Outputtime.struct_time(tm_year=2015, tm_mon=10, tm_mday=29, tm_hour=13,tm_min=48, tm_sec=29, tm_wday=3, tm_yday=302, tm_isdst=0)

The time returned is a time structure which includes 9 attributes which are:

tm_yearReturns the current year
tm_monReturns the current month
tm_mdayReturns the current month day
tm_hourReturns the current hour.
tm_minReturns the current minute
tm_secReturns current seconds
tm_wdayReturns the week day
tm_ydayReturns the year day.
tm_isdstIt returns -1, 0 or 1.

Formatted Time

To retrieve the time in format use asctime().

import time;localtime = time.asctime( time.localtime(time.time()) )
print localtime
Thu Oct 29 13:56:05 2015

Time module:

Time module provides the number of functions, which are used to work with time and for convert between representations.
Time module


Python also provide the facility to display the calendar like as follows:

import calendar
calc = calendar.month(2015,10)
print calc

October 2015Mo  Tu  We  Th  Fr  Sa  Su1     2    3   45     6    7     8    9  10   1112   13  14  15  16  17  1819   20 21  22 23  24   2526  27 28 29  30 31

Calendar Module
Calendar module provides number of functions which is work on calendar. Some functions are –
Calendar ModuleSo this brings us to the end of Python tutorial module. See you in the next one.
Further check out our offer for Python certification.

Leave a Reply

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

Solve : *
29 + 17 =