Data Types in Python
Data Types in Python
Python Data Types are used to define the type of a variable. It defines
what type of data we are going to store in a variable. The data stored in
memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric
characters.
Mapping dict
Boolean bool
None NoneType
1
Python Numeric Data Type
Python numeric data types store numeric values. Number objects are
created when you assign a value to them. For example −
Python supports four different numerical types and each of them have
built-in classes in Python library, called int, bool,
float and complex respectively −
Python's standard library has a built-in function type(), which returns the
class of the given object. Here, it is used to check the type of an integer
and floating point number.
>>> type(123)
<class 'int'>
>>> type(9.99)
<class 'float'>
>>> type(5+6j)
<class 'complex'>
int float
10 0.0 3.14j
2
0O777 15.20 45.j
Open Compiler
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))
# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))
# complex variable.
d=10+3j
print("The type of variable having value", d, " is ", type(d))
>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
3
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'
The plus (+) sign is the string concatenation operator and the asterisk (*)
is the repetition operator in Python.
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
4
Sequence is a collection data type. It is an ordered collection of items.
Items in the sequence have a positional index starting with 0. It is
conceptually similar to an array in C or C++. There are following three
sequence data types defined in Python.
As mentioned, an item in the list may be of any data type. It means that a
list object can also be an item in another list. In that case, it becomes a
nested list.
The values stored in a Python list can be accessed using the slice operator
([ ] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation
operator, and the asterisk (*) is the repetition operator.
5
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
A tuple is also a sequence, hence each item in the tuple has an index
referring to its position in the collection. The index starts from 0.
As in case of a list, an item in the tuple may also be a list, a tuple itself or
an object of any other Python class.
6
Example of Tuple data Type
Open Compiler
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed i.e. lists are
mutable, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated (immutable). Tuples can be thought of as read-only lists.
Open Compiler
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
7
It is represented by the Range class. The constructor of this class accepts
a sequence of numbers starting from 0 and increments to 1 until it
reaches a specified number. Following is the syntax of the function −
Open Compiler
for i in range(5):
print(i)
0
1
2
3
4
Now let's modify above program to print the number starting from 2
instead of 0 −
Open Compiler
for i in range(2, 5):
print(i)
2
3
4
Again, let's modify the program to print the number starting from 1 but
with an increment of 2 instead of 1:
Open Compiler
8
for i in range(1, 5, 2):
print(i)
1
3
This type of data is commonly used when dealing with things like files,
images, or anything that can be represented using just two possible
values. So, instead of using regular numbers or letters, binary sequence
data types use a combination of 0s and 1s to represent information.
Python provides three different ways to represent binary data. They are as
follows −
bytes
bytearray
memoryview
Open Compiler
# Using bytes() function to create bytes
b1 = bytes([65, 66, 67, 68, 69])
print(b1)
9
The result obtained is as follows −
b'ABCDE'
In here, we are using the "b" prefix before a string to automatically create
a bytes object −
Open Compiler
# Using prefix 'b' to create bytes
b2 = b'Hello'
print(b2)
b'Hello'
Open Compiler
# Creating a bytearray from an iterable of integers
value = bytearray([72, 101, 108, 108, 111])
print(value)
bytearray(b'Hello')
Open Compiler
# Creating a bytearray by encoding a string
val = bytearray("Hello", 'utf-8')
10
print(val)
bytearray(b'Hello')
You can create a memory view using various methods. These methods
include using the memoryview() constructor, slicing bytes or bytearray
objects, extracting from array objects, or using built-in functions like
open() when reading from files.
Open Compiler
data = bytearray(b'Hello, world!')
view = memoryview(data)
print(view)
<memory at 0x00000186FFAA3580>
If you have an array object, you can create a memoryview using the
buffer interface as shown below −
Open Compiler
import array
arr = array.array('i', [1, 2, 3, 4, 5])
view = memoryview(arr)
print(view)
11
<memory at 0x0000017963CD3580>
Open Compiler
data = b'Hello, world!'
# Creating a view of the last part of the data
view = memoryview(data[7:])
print(view)
<memory at 0x00000200D9AA3580>
12
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Comma separated items in a set are put inside curly brackets or braces
{}. Items in the set collection can be of different data types.
Note that items in the set collection may not follow the same order in
which they are entered. The position of items is optimized by Python to
perform operations over set as defined in mathematics.
Python's Set is an object of built-in set class, as can be checked with the
type() function.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence,
add/delete/update operations are permitted on a set object, using the
methods in built-in set class. Python also has a set of operators to perform
set manipulation. The methods and operators are explained in latter
chapters
Example of Set
print(set1)
print(set2)
{123, 452, 5, 6}
{'Python', 'JavaScript', 'Java'}
14
>>> type(False)
<class 'bool'>
Open Compiler
a = True
# display the value of a
print(a)
true
<class 'bool'>
Open Compiler
# Returns false as a is not equal to b
a=2
b=4
print(bool(a==b))
# Returns false as a is 0
15
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
False
False
False
False
False
True
Example
Following is an example which converts different values to integer,
floating point and string values respectively −
Open Compiler
print("Conversion to integer data type")
a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3.3") # c will be 3
print (a)
print (b)
print (c)
16
print (a)
print (b)
print (c)
print("Conversion to string")
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"
print (a)
print (b)
print (c)
17