- Data type represent 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
Remark
- In python everything is an object.
- Python contains several inbuilt functions:
- type(): To check the type of variable.
- id(): To get address of the object.
- print(): To print the value.
Example
Python
num = 10
print(type(num))
print(id(num))
Output
PowerShell
10
1673698634320
Int data type
- We can use int data type to represent whole numbers (integral values).
Example
Python
num = 10
print(type(num))
Output
PowerShell
<class 'int'>
Remark
- 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
Decimal form (Base-10)
- It is the default number system in python
- The allowed digits are: 0 to 9
Example
Python
num = 10
print(num)
Output
PowerShell
10
Binary form (Base-2)
- The allowed digits are : 0 & 1
- Literal value should be prefixed with 0b or 0B
Example
Python
num = 0B1111
print(num, type(num))
Output
PowerShell
15 <class 'int'>
Example
Python
num = 0b123
print(num)
Output
PowerShell
SyntaxError: invalid digit '2' in binary literal
Octal Form (Base-8)
- The allowed digits are : 0 to 7
- Literal value should be prefixed with 0o or 0O.
Example
Python
num = 0O123
print(num)
Output
PowerShell
83
Example
Python
num = 0O786
print(num)
Output
PowerShell
SyntaxError: invalid digit '8' in octal literal
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
Example
Python
num1 = 0XFACE
num2 = 0XBeef
print(num1, num2)
Output
PowerShell
64206 48879
Example
Python
num = 0XBeer
print(num)
Output
PowerShell
SyntaxError: invalid hexadecimal literal
Remark
- 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.
Example
Python
num1 = 10
num2 = 0o10
num3 = 0X10
num4 = 0B10
print(num1)
print(num2)
print(num3)
print(num4)
Output
PowerShell
10
8
16
2
Base Conversions
Python provide the following in-built functions for base conversions
bin()
- We can use bin() to convert from any base to binary.
Example
Python
num = 15
print(bin(num))
num = 0o11
print(bin(num))
num = 0X10
print(bin(num))
Output
PowerShell
0b1111
0b1001
0b10000
oct()
- We can use oct() to convert from any base to octal.
Python
num = 10
print(oct(num))
num = 0B1111
print(oct(num))
num = 0X123
print(oct(num))
Output
PowerShell
0o12
0o17
0o443
hex()
- We can use hex() to convert from any base to hexa decimal.
Python
num = 100
print(hex(num))
num = 0B111111
print(hex(num))
num = 0o12345
print(hex(num))
Output
PowerShell
0x64
0x3f
0x14e5
Float data type
- We can use float data type to represent floating point values (decimal values).
Example
Python
num = 1.234
print(type(num))
Output
PowerShell
<class 'float'>
- We can also represent floating point values by using exponential form (scientific notation).
- The main advantage of exponential form is we can represent big values in less memory.
Example
Python
num = 1.2e3
print(num)
Output
PowerShell
1200.0
Remark
- We can represent int values in decimal, binary, octal and hexa decimal forms. But we can represent float values only by using decimal form.
Example
Python
num = 0B11.01
print(num) # SyntaxError: invalid syntax
num = 0o123.456
print(num) # SyntaxError: invalid syntax
num = 0X123.456
print(num) # SyntaxError: invalid syntax
Complex Data Type
- A complex number is of the form a + bj where ‘a’ and ‘b’ contain integers or floating point values.
Example
Python
num = 3 + 5j
print(num)
num = 10 + 5.5j
print(num)
num = 0.5 + 0.1j
print(num)
Output
PowerShell
(3+5j)
(10+5.5j)
(0.5+0.1j)
- In the real part if we use int value the we can specify that either by decimal, octal, binary or hexa decimal form.
- But imaginary part should be specified only by using decimal form.
Example
Python
num = 0B11 + 5j
print(num)
num = 3 + 0B11j
print(num)
Output
PowerShell
(3+5j)
SyntaxError: invalid binary literal
- We can perform operations on complex type values.
Example
Python
num1 = 10 + 1.5j
num2 = 20 + 2.5j
print(num1+num2)
Output
PowerShell
(30+4j)
- Complex data type has inbuilt attributes to retrieve the real part and imaginary part.
Example
Python
num = 10.5 + 3.6j
print(num.real)
print(num.imag)
Output
PowerShell
10.5
3.6
Remark
- We can use complex type generally in scientific Applications and electrical engineering applications.
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
Example
Python
num = True
print(type(num))
Output
PowerShell
<class 'bool'>
- Internally Python represents True as 1 and False as 0
Example
Python
num1 = True
num2 = False
print(num1+num1)
print(num1-num2)
Output
PowerShell
2
1
String data type
- A String is a sequence of characters enclosed within single quotes or double quotes.
Example
Python
str1 = 'ajay'
str2 = "ajay"
print(str1, type(str1))
print(str1, type(str1))
Output
PowerShell
ajay
ajay
- By using single quotes or double quotes we cannot represent multi line string literals.
Python
str1 = "ajay
shukla"
Output
PowerShell
SyntaxError: unterminated string literal (detected at line 1)
- For multi line string literals we should go for triple single quotes(”’) or triple double quotes(“””).
Python
str1 = '''ajay
shukla'''
str2 = """ajay
shukla"""
print(str1)
print(str2)
Output
PowerShell
ajay
shukla
ajay
shukla
- We can also use triple quotes to use single quote or double quote in our String.
Python
str1 = '''This is "character"'''
str2 = """This is 'character'"""
print(str1)
print(str2)
Output
PowerShell
This is "character"
This is 'character'
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.
Example
Python
str1 = 'ajay shukla'
# Forward direction slicing
print(str1[0])
print(str1[1])
print(str1[1:40])
print(str1[1:])
print(str1[:])
print(str1[40])
Output
PowerShell
'a'
'j'
'jay shukla'
'jay shukla'
'ajay shukla'
IndexError: string index out of range
Example
Python
str1 = 'ajay shukla'
# Backward direction slicing
print(str1[-1])
print(str1[-3:-1])
print(str1[-3:])
print(str1[-30])
Output
PowerShell
a
kl
ERROR!
kla
IndexError: string index out of range
Remark
- In Python the following data types are considered as Fundamental Data types.
- int
- float
- complex
- bool
- str
- In python, we can represent char values also by using str type and explicitly char type is not available.
Python
str1 = 'a'
print(type(str1))
Output
PowerShell
<class 'str'>
- long data type is available in Python2 but not in Python3. In Python3 long values also we can represent by using int type only.
Bytes Data Type
- Bytes data type represents a group of byte numbers just like an array.
Python
list1 = [10, 20, 30, 40]
b = bytes(list1)
print(type(b))
print(b[0])
print(b[-1])
for i in b: print(i)
Output
PowerShell
<class 'bytes'>
10
40
10
20
30
40
Remark
- The only allowed values for byte data type are 0 to 255. By mistake if we are trying to provide any other values then we will get value error.
Python
list1 = [10, 255]
for i in bytes(list1): print(i)
list2 = [10, 256]
for i in bytes(list2): print(i)
Output
PowerShell
10
255
ValueError: bytes must be in range(0, 256)
- Once we creates bytes data type value, we cannot change its values, otherwise we will get TypeError. It means bytes is immutable.
Python
list1 = [10, 20, 30, 40]
b = bytes(list1)
b[0] = 100
Output
PowerShell
TypeError: 'bytes' object does not support item assignment
Bytearray Data type
- Bytearray is exactly same as bytes data type except that its elements can be modified.
Python
list1 = [10,20,30,40]
b = bytearray(list1)
for i in b : print(i)
# modify 0th element
b[0]=100
for i in b: print(i)
Output
PowerShell
10
20
30
40
100
20
30
40
List data type
- 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.
- In list;
- Insertion order is preserved.
- Heterogeneous objects are allowed.
- Duplicates are allowed.
- Growable in nature.
- Values should be enclosed within square brackets.
Example
Python
list1 = [10, 10.5, 'ajay', True, 10]
print(list1)
Output
PowerShell
[10, 10.5, 'ajay', True, 10]
- Slicing is applicable in list.
Example
Python
list1 = [10, 20, 30, 40]
print(list1[0])
print(list1[-1])
print(list1[1:3])
# list assignment
list1[0] = 100
print(list1)
Output
PowerShell
10
40
[20, 30]
[100, 20, 30, 40]
- List is growable in nature. i.e. based on our requirement we can increase or decrease the size.
Example
Python
list1 = [10, 20, 30]
# push new element
list1.append("ajay")
print(list1)
# pop element
list1.remove(20)
print(list1) # [10, 30, 'ajay']
# multiply constant term
list2 = list1*2
print(list2) # [10, 30, 'ajay', 10, 30, 'ajay']
Output
PowerShell
[10, 20, 30, 'ajay']
[10, 30, 'ajay']
[10, 30, 'ajay', 10, 30, 'ajay']
Remark
- An ordered, mutable, heterogenous collection of elements is nothing but list, where duplicates also allowed.
Tuple data type
- 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 “()”.
Example
Python
tuple1 = (10, 20, 30, 40)
print(type(tuple1))
# Try to change 0th value
tuple1[0] = 100
# Try to push new element
tuple1.append("ajay")
# Try to remove element
tuple1.remove(10)
Output
PowerShell
<class 'tuple'>
# TypeError: 'tuple' object does not support item assignment
# AttributeError: 'tuple' object has no attribute 'append'
# AttributeError: 'tuple' object has no attribute 'remove'
Remark
- Tuple is the read only version of list.
- Indexing and slicing operation allowed.
Range Data Type
- 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.
Example
Python
for index in range(10): print(index)
Output
PowerShell
0
1
2
3
4
5
6
7
8
9
Form-2: range(10,20)
- Generate numbers from 10 to 19.
Example
Python
for index in range(10, 20): print(index)
Output
PowerShell
10
11
12
13
14
15
16
17
18
19
Form-3: range(10,20,2)
- 2 means increment value.
Example
Python
for index in range(10, 20, 2): print(index)
Output
PowerShell
10
12
14
16
18
- Slicing and indexing applicable in range data type.
Python
rangeObj = range(10, 20)
print(rangeObj[0])
print(rangeObj[10])
Output
PowerShell
10
# IndexError: range object index out of range
- We cannot modify the values of range data type.
Python
rangeObj = range(10, 20)
rangeObj[0] = 100
Output
PowerShell
TypeError: 'range' object does not support item assignment
- We can create a list of values with range data type.
Python
list1 = list(range(10))
print(type(list1))
print(list1)
Output
PowerShell
<class 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- Range not work with float number.
Python
range(1, 10.5)
Output
PowerShell
TypeError: 'float' object cannot be interpreted as an integer
Set Data Type
- If we want to represent a group of values without duplicates where order is not important then we should go for set data type.
- In set;
- 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.
Example
Python
set1 = {100, 0, 10, 200, 10, 'ajay'}
print(set1)
# print first element
print(set1[0])
Output
PowerShell
{0, 100, 'ajay', 10, 200}
# TypeError: 'set' object is not subscriptable
- Set is growable in nature, based on our requirement we can increase or decrease the size.
Python
set1 = {100, 0, 10, 200, 10, 'ajay'}
# Add new element
set1.add(60)
print(set1)
# Remove 100 from set
set1.remove(100)
print(set1)
Output
PowerShell
{0, 100, 'ajay', 200, 10, 60}
{0, 'ajay', 200, 10, 60}
Frozenset Data Type
- It is exactly same as set except that it is immutable. Hence we cannot use add or remove functions.
Example
Python
set1 = {10, 20, 30, 40}
frozenset1 = frozenset(set1)
print(type(frozenset1))
print(frozenset1)
for num in frozenset1: print(num)
# Add new element
frozenset1.add(70)
# Remove element 10
frozenset1.remove(10)
Output
PowerShell
<class 'frozenset'>
frozenset({40, 10, 20, 30})
40
10
20
30
# AttributeError: 'frozenset' object has no attribute 'add'
# AttributeError: 'frozenset' object has no attribute 'remove'
Dict Data Type
- If we want to represent a group of values as key-value pairs then we should go for dict data type.
Example
Python
dict1 = {101:'kuldeep',102:'ajay',103:'amit'}
print(type(dict1))
Output
PowerShell
<class 'dict'>
- 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.
Python
dict1 = {101:'kuldeep',102:'ajay',103:'amit'}
# Assign new value
dict1[101] = 'sunny'
print(dict1)
# We can create empty dictionary as follows
dict2 = { }
# We can add key-value pairs as follows
dict2['a'] = 'apple'
dict2['b'] = 'banana'
print(dict2)
Output
PowerShell
{101: 'sunny', 102: 'ajay', 103: 'amit'}
{'a': 'apple', 'b': 'banana'}
Remark
- Dict is mutable and the order wont 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.
None Data Type
- 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.
Example
Python
def myFunction():
num1 = 10
print(myFunction())
Output
PowerShell
None
Summary of data types
Data Type | Description | Is Immutable | Example |
Int | We can use to represent the whole/integral numbers | Immutable | num1 = 10 print(type(num1)) # <class ‘int’> |
Float | We can use to represent the decimal/floating point numbers | Immutable | num1 = 10.5 print( type(b)) # <class ‘float’> |
Complex | We can use to represent the complex numbers | Immutable | complex1 = 10+5j print(type(complex1)) # <class ‘complex’> print(complex1.real) # 10.0 print(complex1.imag) #5.0 |
Bool | We can use to represent the logical values(Only allowed values are True and False) | Immutable | flag = True type(flag) # <class ‘bool’> |
Str | To represent sequence of Characters | Immutable | str1 = ‘ajay’ print(type(str1)) # <class ‘str’> |
bytes | To represent a sequence of byte values from 0-255 | Immutable | list1 = [1,2,3,4] bytes1 = bytes(list1) print(type(bytes1)) # <class ‘bytes’> |
bytearray | To represent a sequence of byte values from 0-255 | Mutable | list1 = [10,20,30] bytesarray1 = bytearray(list1) print(type(bytesarray1)) # <class ‘bytearray’> |
range | To represent a range of values | Immutable | range1 = range(10) range2 = range(0,10) range3 = range(0,10,2) |
list | To represent an ordered collection of objects | Mutable | list1 = [10,11,12,13,14,15] print(type(list1)) # <class ‘list’> |
tuple | To represent an ordered collections of objects | Immutable | tuple1 = (1,2,3,4,5) print(type(tuple1)) # <class ‘tuple’> |
set | To represent an unordered collection of unique objects | Mutable | set1 = {1,2,3,4,5,6} print(type(set1)) # <class ‘set’> |
frozenset | To represent an unordered collection of unique objects | Immutable | set1 = {11, 2, 3, ‘ajay’, 100, ‘amit’} fs = frozenset(set1) print(type(fs)) # <class ‘frozenset’> |
dict | To represent a group of key value pairs | Mutable | dict1 = {101:’kuldeep’,102:’ajay’,103:’amit’} print(type(dict1)) # <class ‘dict’> |
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!