0% found this document useful (0 votes)
12 views

4. Type Casting

The document explains typecasting in Python, detailing various built-in functions such as int(), float(), complex(), bool(), and str() for converting between different data types. It also covers fundamental data types, their mutability, and specific characteristics of data types like bytes, bytearray, list, tuple, range, set, frozenset, and dict. Additionally, it highlights the importance of immutability and memory management in Python's data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

4. Type Casting

The document explains typecasting in Python, detailing various built-in functions such as int(), float(), complex(), bool(), and str() for converting between different data types. It also covers fundamental data types, their mutability, and specific characteristics of data types like bytes, bytearray, list, tuple, range, set, frozenset, and dict. Additionally, it highlights the importance of immutability and memory management in Python's data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Type

Casting
We can convert one type value to another type. This conversion is called Typecasting
or Type conversion.
The following are various inbuilt functions for type casting.

1. int()
2. float()
3. complex()
4. bool()
5. str()

1.int():

We can use this function to convert values from other types to int

Eg:

>>> int(123.987)

123

>>> int(10+5j)

TypeError: can't convert complex to int

>>> int(True)

>>> int(False)

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

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

2. 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 float

>>> 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:
1. We can convert any type value to float type except complex type.

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

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

4. bool():

We can use this function to convert other type values to bool type.

Eg:
1) bool(0)==>False

2) bool(1)==>True

3) bool(10)===>True

4) bool(10.5)===>True

5) bool(0.178)==>True

6) bool(0.0)==>False

7) bool(10-2j)==>True

8) bool(0+1.5j)==>True

9) bool(0+0j)==>False

10) bool("True")==>True

11) bool("False")==>True

12) bool("")==>False
5. str():

We can use this method to convert other type values to str

type Eg:

1) >>> str(10)
2) '10'
3) >>> str(10.5)

5) >>> str(10+5j)
6) '(10+5j)'
7) >>> str(True)

Fundamental Data Types vs Immutability:


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-chageable behaviour is called
immutability.

In Python if a new object is required, then PVM wont 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.

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.

Eg:

1) >>> a=10
2) >>> b=10
3) >>> a is b
4) >>> True
5) >>> id(a)
6) 1572353952
7) >>> id(b)

9) >>>

>>> a=10 >>> a=10+5j >>> a=True >>> a='durga'

>>> b=10 >>> b=10+5j >>> b=True >>> b='durga'

>>> id(a) >>> a is b >>> a is b >>> a is b

1572353952 False True True

>>> id(b) >>> id(a) >>> id(a) >>> id(a)


bytes Data Type:

bytes data type represens a group of byte numbers just like an

array. Eg:

Conclusion 1:

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.

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

bytearray Data type:


bytearray is exactly same as bytes data type except that its elements can be

modified. Eg 1:

1) x=[10,20,30,40]

2) b = bytearray(x)

3) b[1]=777

4) print(b)
Eg 2:

1) >>> x =[10,256]
2) >>> b = bytearray(x)
3) 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.

1. insertion order is preserved


2. heterogeneous objects are allowed
3. duplicates are allowed
4. Growable in nature
5. values should be enclosed within square brackets.

Eg:

1) list=[10,10.5,'durga',True,10]

2) print(list) # [10,10.5,'durga',True,10]

Eg:

1) list=[10,20,30,40]
2) >>> list[0]
3) 10
4) >>>list[-1]
5) 40
6) >>> list[1:3]
7) [20, 30]
list is growable in nature. i.e based on our requirement we can increase or decrease the
size.

1) >>> list=[10,20,30]
2) >>> list.append("durga")
3) >>> list

5) >>> list.remove(20)
6) >>> list
7) [10, 30, 'durga']
list2=list*2
9) >>> list2
10) [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 it is immutable.i.e we
cannot chage values.

Tuple elements can be represented within

parenthesis. Eg:

1) t=(10,20,30,40)
2) type(t)
3) <class 'tuple'>
4) t[2]=5
5) TypeError: 'tuple' object does not support item assignment
6) >>> t.append("durga")
7) AttributeError: 'tuple' object has no attribute 'append'

9) 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.
Form-1: range(10)
generate numbers from 0 to 9

Eg:
r=range(10)
for i in r : print(i) 0 to 9

Form-2: range(10,20)

generate numbers from 10 to 19

r = range(10,20)
for i in r : print(i) 10 to 19

Form-3: range(10,20,2)

2 means increment value

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

Eg:
r[0]=100
TypeError: 'range' object does not support item

assignment We can create a list of values with range

data type

Eg:

1) >>> l = list(range(10))
2) >>> l
3) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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.
1. insertion order is not preserved
2. duplicates are not allowed
3. heterogeneous objects are allowed
4. index concept is not applicable
5. It is mutable collection
6. Growable in

nature Eg:

1) s={100,0,10,200,10,'durga'}
2) s # {0, 100, 'durga', 200, 10}

3) s[0] ==>TypeError: 'set' object does not support indexing

4)

5) set is growable in nature, based on our requirement we can increase or decrease the size.

6)

7) >>> s.add(60)

8) >>> s

9) {0, 100, 'durga', 200, 10, 60}

10) >>> s.remove(100)

11) >>> s

12) {0, 'durga', 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.

1) >>> s={10,20,30,40}
2) >>> fs=frozenset(s)
3) >>> type(fs)

5) >>> fs
6) frozenset({40, 10, 20, 30})
7) >>> for i in fs:print(i)

9) 40
10) 10
11) 20

13)
14) >>> fs.add(70)
15) AttributeError: 'frozenset' object has no attribute 'add'

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

Eg:

1. >>> d={101:'durga',102:'ravi',103:'shiva'}
2. >>> d[101]='sunny'
3. >>> d

5.
6. We can create empty dictionary as follows
7. d={ }

9. d['a']='apple'
10. d['b']='banana'
11. print(d)

Note: dict is mutable and the order wont be preserved.


Note:

1. In general we can use bytes and bytearray data types to represent binary
information like images,video files etc
2. 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.
3. In Python there is no char data type. Hence we can represent char values also by
using str type.

You might also like