bing
Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
×
UPTO
50%
OFF!
Intellipaat
Intellipaat
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Datatypes:

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

Learn Python in 16 hrs from experts



Datatypes in Python

Numbers

In python, numbers are divided into five datatypes.

They are:

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

Integers

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

e.g.:

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

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

Operators Description
s1 = ‘  ’ Empty string
s2 = “a string” Double quotes
block = ‘‘‘…’’’ Triple-quoted blocks
s1 + s2 Concatenate
s2 * 3 repeat
s2[i] i=Index
s2[i:j] slice
len(s2) length
“a %s parrot” % ‘dead’ String formatting
for x in s2 Iteration
‘m’ in s2 membership

Table:  String Backslash Characters

Operators Description
\newline Ignored (a continuation)
\n Newline (ASCII linefeed)
\\ Backslash (keeps one \)
\v Vertical tab
\’ Single quote (keeps ‘)
\t Horizontal tab
\” Double quote (keeps “)
\r Carriage return
\a ASCII bell
\f Form feed
\b Backspace
\0XX Octal value XX
\e Escape (usually)
\xXX Hex value XX
\000 Null (doesn’t end string)

Example: Program to concatenate two strings

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

Built in string methods:

Method Description
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.

Wish to Learn Python? Click Here

List:

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]
list2=[“hello”,”intellipaat”]

Creating Multi-Dimensional Lists:

One dimensional:

init_list = [0]*3
print(init_list)
output:
[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
print(two_dim_list)
[[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:

Example-1:

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

Example-2:

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
print(two_dim)
[[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

print(two_dim)

[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

extend():

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

L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
L1.extend(L2)
print(L1)
[‘a’, ‘b’, ‘c’, ‘d’]

append():

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

L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
L1.extend(L2)
print(L1)
[‘a’, ‘b’, ‘c’, ‘d’]

Accessing a list:

To access a list in python we use indexing.

[index]

For instance,

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

Accessing a list using Reverse indexing:

print(list1[-1])
print(list1[-3])
Output:
5
3

Slicing a Python List:

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

Other common list operations:

Iterate a list

for element in list1:

    print(element)

Update/ add

list1[4] = ‘number’print(list1)

output:

[1, 2, 3, 4, ‘number’]

list1[4:7] = [“Apple”,”Mango”,”Banana”]

print(list1)

output:

[1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

list1.insert(0,33)

print(list1)

output:

[33, 1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

list1.insert(6,29)

print(list1)

output:

[33, 1, 2, 3, 4, ‘Apple’, 29, ‘Mango’, ‘Banana’]

Remove/Delete elements:

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

print(list1)

output:

[1, 2, 4, 5]

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

list1.remove(4)

print(list1)

output:

[1, 2, 3, 5]

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

print(list1.pop(1))

print(list1)

output:

2

[1, 3, 4, 5]

Sorting list:

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

list1.sort()

Sort in ascending order:

list1 = [1,3,2,4,5,9,6]
list1.sort()
print(list1)
output:
[1, 2, 3, 4, 5, 6, 9]

Sort in descending order:

list1 = [1,3,2,4,5,9,6]
list1.sort(reverse=True)
print(list1)output:
[9, 6, 5, 4, 3, 2, 1]

Python list methods and functions:

Method Description
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.sort Sort 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:

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)) 
output:
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])
output:
The tuple: (1, 2, 3, 4, 5, 6) Length: 6
tuple1[0]: 1

Via reverse indexing

tuple1 = (1,2,3,4,5,6)
tuple1[-1]output:
6

Via slicing operator

tuple1[1:]
output:
(2, 3, 4, 5, 6)
tuple1[1:5]
output:
(2, 3, 4, 5)

Performing operations in tuple

Modifying tuple

Tuples in python are immutable.

Deleting tuple

Tuples in python are immutable.

Set:

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”}
print(myset)
  • 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”}
myset.add(“orange”)
print(myset)

Using update():

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

Length of a Set:

myset = {“apple”, “banana”, “cherry”}
print(len(myset))

Remove items:

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

myset = {“apple”, “banana”, “cherry”}
myset.remove(“banana”)
print(myset)

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

myset = {“apple”, “banana”, “cherry”}
myset.discard(“banana”)
print(myset)

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()
print(x)
print(myset)

Empty a set completely:

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

myset = {“apple”, “banana”, “cherry”}
myset.clear()
print(myset)

Using del():

myset = {“apple”, “banana”, “cherry”}
del myset
print(myset)

Common set methods:

Method Description
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:

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’)
print(My_dict)

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:

My_dict[‘fruit’]=‘Mango’
print(My_dict)

Loop through a dictionary:

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

for x in My_dict:
print(My_dict[x])

Adding items:

My_dict[‘weight’] =10
print(thisdict)

Removing items from a dictionary:

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

My_dict.pop(‘weight’)
print(My_dict)

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

My_dict.del(‘weight’)
print(My_dict)

Removing the complete dictionary:

del My_dict
print(My_dict)

Using clear():
clear() empties the dictionary

My_dict.clear()
print(My_dict)

Dictionary length:

print(len(My_dict))

Check all the keys:

print(My_dict.keys())

Check all the values:

print(My_dict.values())

Common dictionary methods:

Method Description
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.

Boolean:

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 

output:

True

len(str) != 11

output:

False

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

Output:

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

print(number_int+number_string)

output:

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 :

(required_datatype)(expression)

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

Output:

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.

Method Description
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:

Attribute Description
tm_year Returns the current year
tm_mon Returns the current month
tm_mday Returns the current month day
tm_hour Returns the current hour.
tm_min Returns the current minute
tm_sec Returns current seconds
tm_wday Returns the week day
tm_yday Returns the year day.
tm_isdst It 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
Output
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

Calendar

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

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

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

Previous Next

Download Interview Questions asked by top MNCs in 2018?

Learn SQL in 16 hrs from experts



"0 Responses on Datatypes in Python"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.
top

Sales Offer

Sign Up or Login to view the Free Datatypes in Python.