Python Data Types
In this tutorial, we are going to discuss about the Python Data Types.
- Data Type represents the type of data present inside a variable.
- In Python we are not required to specify the type explicitly. Based on value provided, the type will be assigned automatically. Hence Python is dynamically Typed Language.
Python contains the following inbuilt data types
- Int
- Float
- Complex
- Bool
- Str
- Bytes
- Bytearray
- Range
- List
- Tuple
- Set
- Frozenset
- Dict
- None
Note
Python contains several inbuilt functions.
1. type() to check the type of variable
2. id() to get address of object
3. print() to print the value
In Python everything is an Object.
1. int Data Type
We can use int data type to represent whole numbers (integral values).
E.g
a = 10
type(a) #int
Note
- In Python2 we have long data type to represent very large integral values.
- But in Python3 there is no long type explicitly and we can represent long values also by using int type only.
We can represent int values in the following ways
- Decimal form
- Binary form
- Octal form
- Hexa decimal form
1. Decimal Form (Base-10)
- It is the default number system in Python
- The allowed digits are: 0 to 9
E.g
a = 10
b = 20
c = 30
2. Binary Form (Base-2)
- The allowed digits are : 0 & 1
- Literal value should be prefixed with 0b or 0B
E.g
a = 0B1111
a = 0B123
a = b111
3. Octal Form (Base-8)
- The allowed digits are : 0 to 7
- Literal value should be prefixed with 0o or 0O.
E.g
a = 0o123
a = 0o786
4. Hexa Decimal Form (Base-16)
- The allowed digits are: 0 to 9, a-f (both lower and upper cases are allowed)
- Literal value should be prefixed with 0x or 0X
E.g
a = 0XFACE
a = 0XBeef
a = 0XBeer
Note
Being a programmer we can specify literal values in decimal, binary, octal and hexa decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0o10
c=0X10
d=0B10
print(a) - 10
print(b) - 8
print(c) - 16
print(d) - 2
Base Conversions
Python provide the following in-built functions for base conversions.
1. bin(): We can use bin() to convert from any base to binary.
>>> bin(15)
'0b1111'
>>> bin(0o11)
'0b1001'
>>> bin(0X10)
'0b10000'
2. oct(): We can use oct() to convert from any base to octal
>>> oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> oct(0X123)
'0o443'
3. hex(): We can use hex() to convert from any base to hexadecimal.
>>> hex(100)
'0x64'
>>> hex(0B111111)
'0x3f'
>>> hex(0o12345)
'0x14e5'
2. Float Data Type
We can use float data type to represent floating point values (decimal values)
E.g
f = 1.234
type(f) float
We can also represent floating point values by using exponential form (Scientific Notation)
E.g
f = 1.2e3
Here instead of 'e' we can use 'E'
print(f) 1200.0
The main advantage of exponential form is we can represent big values in less memory.
Note
We can represent int values in decimal, binary, octal and hexadecimal forms. But we can represent float values only by using decimal form.
>>> f=0B11.01
File "<stdin>", line 1
f=0B11.01 4) ^
SyntaxError: invalid syntax
>>> f=0o123.456
SyntaxError: invalid syntax
>>> f=0X123.456
SyntaxError: invalid syntax
3. Complex Data Type
A complex number is of the form
‘a’ and ‘b’ contain Integers OR Floating Point Values.
E.g
3 + 5j
10 + 5.5j
0.5 + 0.1j
In the real part if we use int value then we can specify that either by decimal, octal, binary or hexa decimal form. But imaginary part should be specified only by using decimal form.
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
Even we can perform operations on complex type values.
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j) 6)
>>> type(c)
<class 'complex'>
Note
Complex data type has some inbuilt attributes to retrieve the real part and imaginary part.
c = 10.5+3.6j
c.real ==> 10.5
c.imaginary ==> 3.6
We can use complex type generally in scientific Applications and electrical engineering Applications.
4. bool Data Type
We can use this data type to represent boolean values. The only allowed values for this data type are True and False.
Internally Python represents True as 1 and False as 0
b = True
type(b) ==> bool
E.g
a = 10
b = 20
c = a < b
print(c) ==> true
True+True ==> 2
True-False ==> 1
5. str Data Type
- str represents String data type.
- A String is a sequence of characters enclosed within single quotes or double quotes.
s1 = 'Waytoeasylearn'
s1 = "Waytoeasylearn"
By using single quotes or double quotes we cannot represent multi line string literals.
s1 = '''Wayto
easylearn'''
For this requirement we should go for triple single quotes(”’) or triple double quotes(“””)
s1 = '''Wayto
easylearn'''
s1 = """Wayto
easylearn"""
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
' This is " Character '
We can embed one string in another string
'''This "Python tutorial is very helpful" for python learners'''
Slicing of Strings
- slice means a piece
- [ ] operator is called slice operator, which can be used to retrieve parts of String.
- In Python Strings follows zero based index.
- The index can be either +ve or -ve.
- +ve index means forward direction from Left to Right
- -ve index means backward direction from Right to Left
>>> s = "Ashok"
-5 -4 -3 -2 -1
A s h o k
>>> s[0]
'A'
>>> s[1]
's'
>>> s[-1]
'k'
>>> s[40]
IndexError: string index out of range
>>> s[1:40]
'shok'
>>> s[1:]
'shok'
>>> s[:4]
'Asho'
>>> s[:]
'Ashok'
>>> s*3
'AshokAshokAshok'
>>> len(s)
5
Note
1. In Python the following data types are considered as Fundamental Data types
- int
- float
- complex
- bool
- str
2. In Python, we can represent char values also by using str type and explicitly char type is not available.
>>> c='a'
>>> type(c)
<class 'str'>
3. long Data Type is available in Python2 but not in Python3. In Python3 long values also we can represent by using int type only.
4. In Python we can present char Value also by using str Type and explicitly char Type is not available.
6. bytes
bytes data type represents a group of byte numbers just like an array.
x = [10,20,30,40]
b = bytes(x)
type(b) ==> bytes
print(b[0])
10
print(b[-1])
40
>>> for i in b : print(i)
10
20
30
40
Note
- The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any other values then we will get value error.
- Once we creates bytes data type value, we cannot change its values, otherwise we will get TypeError.
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: 'bytes' object does not support item assignment
7. bytearray
bytearray is exactly same as bytes data type except that its elements can be modified.
x=[10,20,30,40]
b = bytearray(x)
for i in b : print(i)
10
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
>>> x =[10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)
8. List
If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type.
- Insertion Order is preserved
- Heterogeneous Objects are allowed
- Duplicates are allowed
- Growable in nature
- Values should be enclosed within square brackets.
list=[10,10.5,'ashok',True,10]
print(list) # [10,10.5,'ashok',True,10]
list is growable in nature. i.e., based on our requirement we can increase or decrease the size.
>>> list=[10,20,30]
>>> list.append("ashok")
>>> list
[10, 20, 30, 'ashok']
>>> list.remove(20)
>>> list
[10, 30, 'ashok']
>>> list2 = list*2
>>> list2
[10, 30, 'ashok', 10, 30, 'ashok']
Note
An ordered, mutable, heterogeneous collection of elements is nothing but list, where duplicates also allowed.
9. Tuple
- Tuple data type is exactly same as list data type except that it is immutable.i.e we cannot change values.
- Tuple elements can be represented within parenthesis.
t = (10,20,30,40)
type(t)
<class 'tuple'>
t[0]=100
TypeError: 'tuple' object does not support item assignment
>>> t.append("ashok")
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove(10)
AttributeError: 'tuple' object has no attribute 'remove'
Note
tuple is the read only version of list.
10. range
- range Data Type represents a sequence of numbers.
- The elements present in range Data type are not modifiable. i.e range Data type is immutable.
Form 1: range(10)
generate numbers from 0 to 9.
E.g
r = range(10)
for i in r : print(i)
0 to 9
Form-2: range(10, 20)
generate numbers from 10 to 19.
E.g
r = range(10,20)
for i in r : print(i)
10 to 19
Form-3: range(10, 20, 2)
2 means increment value
E.g
r = range(10,20,2)
for i in r : print(i)
10,12,14,16,18
We can access elements present in the range Data Type by using index.
r = range(10,20)
r[0] ==> 10
r[15] ==> IndexError: range object index out of range
We cannot modify the values of range data type
r[0] = 100
TypeError: 'range' object does not support item assignment
We can create a list of values with range data type
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
11. set
If we want to represent a group of values without duplicates where order is not important then we should go for set Data Type.
- Insertion order is not preserved
- Duplicates are not allowed
- Heterogeneous objects are allowed
- Index concept is not applicable
- It is mutable collection
- Growable in nature
s={100,0,10,200,10,'ashok'}
s # {0, 100, 'ashok', 200, 10}
s[0] ==> TypeError: 'set' object does not support indexing
set is growable in nature, based on our requirement we can increase or decrease the size.
>>> s.add(60)
>>> s
{0, 100, 'ashok', 200, 10, 60}
>>> s.remove(100)
>>> s
{0, 'ashok', 200, 10, 60}
12. frozenset
- It is exactly same as set except that it is immutable.
- Hence we cannot use add or remove functions.
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:print(i)
40
10
20
30
>>> fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
13. dict
If we want to represent a group of values as key-value pairs then we should go for dict data type.
E.g
d = {101:'ashok',102:'sai',103:'raju'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value.
>>> d={101:'ashok',102:'sai',103:'raju'}
>>> d[101]='sunny'
>>> d
{101: 'sunny', 102: 'sai', 103: 'raju'}
# We can create empty dictionary as follows
d={ }
We can add key-value pairs as follows
d['a']='apple'
d['b']='banana'
print(d)
Note
- dict is mutable and the order won’t be preserved.
- In general we can use bytes and bytearray data types to represent binary information like images, video files etc
- In Python2 long data type is available. But in Python3 it is not available and we can represent long values also by using int type only.
- In Python there is no char data type. Hence we can represent char values also by using str type.
14. None
- None means nothing or No value associated.
- If the value is not available, then to handle such type of cases None introduced.
- It is something like null value in Java.
def m1():
a=10
print(m1())
None
Escape Characters
In String literals we can use escape characters to associate a special meaning.
>>> s="Welcome to \nWaytoeasylearn"
>>> print(s)
Welcome to
Waytoeasylearn
>>> s="Welcome to\tWaytoeasylearn"
>>> print(s)
Welcome to Waytoeasylearn
>>> s="This is " symbol"
File "<stdin>", line 1
s="This is " symbol"
^ SyntaxError: invalid syntax
>>> s="This is \" symbol"
>>> print(s)
This is " symbol
The following are various important escape characters in Python
\n ==> New line
\t ==> Horizontal Tab
\r ==> Carriage Return
\b ==> Back Space
\f ==> Form Feed
\v ==> Vertical Tab
\' ==> Single Quote
\" ==> Double Quote
\\ ==> Back Slash Symbol
Constants
- Constants concept is not applicable in Python.
- But it is convention to use only uppercase characters if we don’t want to change value.
- MAX_VALUE = 10
- It is just convention but we can change the value.
That’s all about the Python Data Types. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Python language.!!