We can convert one type value to another type. This conversation is called Typecasting or Type coercion.
The following are various inbuilt functions for type casting.
- int()
- float()
- complex()
- bool()
- str()
int()
We can use this function to convert values from other types to int
- >>> int(123.987)
- 123
- >>> int(10+5j)
- TypeError: can’t convert complex to int
- >>> int(True)
- 1
- >>> int(False)
- 0
- >>> int(“10”)
- 10
- >>> int(“10.5”)
- ValueError: invalid literal for int() with base 10: ’10.5'
- >>> int(“ten”)
- ValueError: invalid literal for int() with base 10: ’ten'
- >>> int(“0B1111”)
- ValueError: invalid literal for int() with base 10: ‘0B1111'
Note:
- We can convert from any type to int except complex type
2. If we want to convert str type to int type, compulsary str should contain only integral value and should be specified in base-10
float()
We can use float() function to convert other type values to float type.
- >>> float(10)
- 10.0
- >>> float(10+5j)
- TypeError: can’t convert complex to that
- >>> float(True)
- 1.0
- >>> float(False)
- 0.0
- >>> float(“10”)
- 10.0
- >>> float(“10.5)
- 10.5
- >>> float(“ten”)
- ValueError: could not convert string to float: ’ten'
- >>> float(“0B1111”)
- ValueError: could not convert string to float: ‘0B1111’
Note:
- We can convert any type value to float type except complex type.
- Whenever we are trying to convert str type to float type compulsary str should be either integral or floating point literal and should be specified only in base-10.
Complex():
- We can use complex() function to convert other types to complex type.
Form-1 complex(x)
We can use this function to convert x into complex number with real part x and imaginary part 0.
Eg:
- complex(10)==>10+0j
- complex(10.5)===>10.5+0j
- complex(True)==>1+0j
- complex(False)==>0j
- complex(“10”)==>10+0j
- complex(“10.5”)==>10.5+0j
- complex(“ten”)
- ValueError: complex() arg is a malformed string
Form-2 complex(x,y)
We can use this method to convert x and y into complex number such that x will be real part and y will be imaginary part.
Eg: complex(10, -2) —> 10-2j
complex(True, False) —> 1+0j
bool()
We can use this function to convert other type values to bool type.
- bool(0) —> False
- bool(1) —> True
- bool(10) —> True
- bool(10.5) —> True
- bool(0.178) —> True
- bool(0.0) —> False
- bool(10-2j) —> True
- bool(0+1.5j) —> True
- bool(0+0j) —> False
- bool(“True”) —> True
- bool(“False”) —> True
- bool(“”) —> False
bool(x)
If X is int datatype
- 0 means false
- Non-zero means true
If X is float datatype
- If total number value is zero then the result is false otherwise the result is true
If X is Complex datatype
- If both real and imaginary parts are zero .i.e 0+0j then the result is false otherwise the result is true
If X is str datatype
- If x is empty string then the result is false otherwise the result is true
str():
We can use this method to convert other type values to str type.
- >>> str(10)
- ’10'
- >>> str(10.5)
- ’10.5'
- >>> str(10+5j)
- ‘(10+5j)'
- >>> str(True)
- ’True'
Fundamental Data types vs Immuntability:
- All fundamental data types are immutable. i.e once we creates an object, we cannot perform any changes in that object. If we are trying to change then with those changes a new object will be created. This non-changeable behavior is called immutability.
- In python if a new object is required, then PVM. Won’t create object immediately. First it will check is any object available with the required content or not. If available then existing object will be reused. If it is not available then only a new object will be created. The advantage of this approach is memory utilization and performance will be improved.
3. But the problem in this approach is, several references pointing to the same object, by using one reference if we are allowed to change the content in the existing object then the remaining references will be effected. To prevent this immutability concept is required. According to this once creates an object we are not allowed to change content. If we are trying to change with those changes a new object will be created.
>>> a = 10
>>> b = 10
>>> a = b
True
>>> id(a)
1572353952
>>> id(b)
1572353952
>>>
|
>>> a=10+5j
>>> b=10+5j
>>> a is b
False
>>> id(a)
15980256
>>> id(b)
15979944
|
>>> a=True
>>> b=True
>>> a Is b
True
>>> id(a)
1572172624
>>> id(b)
1572172624
|
>>> a=‘durga’
>>> b=‘durga’
>>> a is b
True
>>> id(a)
16378848
>>> id(b)
16378848
|
Bytes data type:
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
Conclusion 1: The only allowed values for byte data type are 0 to 256. By mistakes if we are trying to provide any other values then we will get value error.
Conclusion 2: once we creates bytes data type value, we cannot change its values, otherwise we will get TypeError.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: ‘bytes’ object does not support item assignment
Byte array data type:
Byte array 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
Eg:2
>>> x=[10,256]
>>> b= byte array(x)
valueError: byte must be in range(0, 256)
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.
Insertion order is preserved
Heterogeneous objects are allowed
Duplicates are allowed
Growable in nature
Values should be enclosed within square brackets
Eg:
list=[10,10.5,’durga’,True,10]
print(list) # [10,10.5,’durga’,True,10]
Eg:
list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[ 20, 30]
>>> list[0]=100
>>> for i in list:print(i)
…
100
20
30
40
List in growable in nature. i.e based on our requirement we can increase or decrease the size.
>>> list=[10,20,30]
>>> list.append(“durga”)
>>> list
[10,20,30, ‘durga’]
>>> list.remov(20)
>>> list
[10,30, ‘durga’]
>>> list2=list*2
>>> list2
[10,30, ‘durga’, 10,30, ‘durga’]
Note: 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 is immutable i.e we cannot change value.
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(“durga”)
AttributeError: : ‘tuple' object has no attribute ‘append’
>>> t.removal(10)
AttributeError: ’tuple’ object has no attribute ‘remove’
Note: tuple is the read only version of list.
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.
Eg:
r = range(10)
for i in r : print(i) —> 0 to 9
Form-2: range(10,20)
Generate numbers from 10 to 19
Eg:
r = range(10,20)
for i in r : print(i) —> 10 to 19
Form3: range(10, 20, 2)
2 means increment value
Eg:
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
Eg:
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.
Eg:
r[0] = 100
TypeError : ‘range’ object does not support
We cannot create a list of values with range data type.
Eg:
>>> I = list(range(10)))
>>> I
[0,1,2,3,4,5,6,7,8,9]
Set Data type
If we want to represent a group if 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 appilable
It is mutable collection
Growable in nature
Eg:
s={100,0,10,200,10,’durga’}
s# {0,100,’durga’, 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, ‘durga’, 200, 10, 60)
>>> s.remove(100)
>>> s
(0, ‘durga’, 200, 10, 60)
Frozen set data type
It is exactly same as set except that it is immutable;e.
Hence we cannot use add or remove functions.
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(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’
dict data type
If we want to represent a group of values as key-value pairs then we should go for dict data type.
Eg: d = {101:’durga’,102:’ravi’,103:’shiva’}
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:’durga’,102:’ravi’,103:’shiva’}
>>> d[101]=’sunny’
>>> d
(101:’sunny’, 102:’ravi’, 103:’shiva’}
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 byte array 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 datatype, hence we can represent char values also by using str type.
Datatype | Description | Is immutable ? | Example |
Int |
We can use to
Represent the whole/integral numbers
| Immutable |
>>> a=10
>>> type(a)
<class ‘int’>
|
Float | We can use to represent the decimal/floating point numbers | Immutable |
>>> b=10.5
>>> type(b)
<class ‘float’>
|
Complex | We can use to represent the complex numbers | Immutable |
>>> c=10+5j
>>> type(c)
<class ‘complex’>
>>> c.real
10.0
>>> c.imag
5.0
|
Bool | We can use to represent the logical values ( only allowed values are true and false ). | Immutable |
>>> flag=True
>>> flag=false
>>> type(flag)
<class ‘bool’>
|
Str | To represent the sequence of characters | Immutable |
>>>s=‘durga’
>>>type(s)
<class ’str’>
>>>s=“durga”
>>>s=‘’’Durga Software solutions… Ameerpet’’'
>>> type(s)
<class ’str’>
|
Bytesarray | To represent a sequence of byte values from 0-255 | mutable |
>>> list[10,20,30]
>>> b=bytearray(list)
>>> type(ba)
<class ‘bytearray’>
|
bytes | To represent a sequence of byte values from 0-255 | immutable |
>>> list[1,2,3,4]
>>> b=bytes[list]
>>> type(b)
<class ‘bytes’>
|
Range | To represent a range of values | Immutable |
>>> r=range(10)
>>> r1=range(0,10)
>>> r2=range(0,10,2)
|
List | To represent an ordered collection of objects | Mutable |
>>> I=[10,11,12,13,14,15]
>>> type(I)
<class ‘list’>
|
Tuple | To represent an ordered collection of objects | Immutable |
>>> t=(1,2,3,4,5)
>>> type(t)
<class ’tuple’>
|
Set | To represent an unordered collection of unique objects | mutable |
>>> s={1,2,3,4,5,6}
>>> type(s)
<class ’set’>
|
frozenset | To represent an unordered collection of unique objects | Immutable |
>>> s={11,2,3,’Durga’,100,’Ramu’}
>>> fs=frozenset(s)
>>> type(fs)
<class ‘frozen set’>
|
dict | To represent a group of key value pairs | Mutable |
>>>
d = {101:’durga’, 102:’rams’, 103:’hard’}
type(d)
<class ‘dict’>
|
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.
Eg:
def m1():
a=10
Print(m1())
None
No comments:
Post a Comment