blog image

In this tutorial we will learn in detail about the data type in python programming language and their uses in various cases.

Basically datatype represent the types of data stored into a variable or memory.

Types of Data-Type:

1.Built-in datatype

2.User define datatype

1.buit-in datatype

it is the data type that is provided by thepython programming.

1.None: it represent the object that doesnot contain any value

2.Numeric datatype:

i.int: represent the whole number system

ii.float: represent the decimal numbers

iii.complex: it represent the number that is written in the form of a+bj

   where : a-> real part of the number

                b->imaginary part

                j->square root value of -1

a=1+2j
b=3-4j
print(a+b)
print(a-b)
print(a*b)
print(a/b)

"""
(4-2j)
(-2+6j)
(11+2j)
(-0.2+0.4j)
"""

iv: boolean: it represent True as 1 and False as 0

print(True+True)
print(True-False)
print(False-True)
print(True-True)
"""
2
1
-1
0
"""

3.Sequence type

i.string: 

It is the group of characters. in python programmimg, string support the indexing.

#string 
a='Nepal'
print(a[0])
print(a[-1])
print(a[::-1]) #for reverse string

"""
N
l
lapeN
"""

#string function
bio="Amrit panta is My Name"
print(bio.upper())
print(bio.lower())
print(bio.swapcase())
print(bio.title())
print(bio.isdigit())
print(bio.isalnum())
print(bio.isspace())
print(bio.split(" "))
print("+".join(bio))
"""
AMRIT PANTA IS MY NAME
amrit panta is my name
aMRIT PANTA IS mY nAME
Amrit Panta Is My Name
False
False
False
['Amrit', 'panta', 'is', 'My', 'Name']
A+m+r+i+t+ +p+a+n+t+a+ +i+s+ +M+y+ +N+a+m+e
"""

ii.list

it contain the group of the elements ans can store different types of elements which can be modified. list are the dynamic which means the size is not fixed and represents using the square bracket [ ].

#list 
bio=["amrit",'engineer',23,5.5,True]
print(bio[1])
print(bio[-1])
bio[3]=6.6
print(bio[3])


"""
engineer
True
6.6
"""

#lst manipulation
1.lst.len()
2.lst.append(5)
3.lst.insert(position,new_element)
4.lst.pop() #remove last element from existing lst
5.lst.pop(n) #remove the element specified by position number and return removed element
6.lst.remove(element) # remove the first occurance of element from lsit
7.lsit.index(element) #return the index of first occurance of the element
8.lst.reverse()  # to reverse the lsit
9.lst.extend(new_lst) # to append the another lst or iterable object at the end
10.lst.count(element) # return the count of element
11.lst.sort() # sort lst in ascending order
12.lst.sort(reverse=True,key=len) # sort the lst in descending order according length
13.lst.clear() # delete all element from lst
14.b=[1,2,3,4,5].copy() # copying lst
15.result=[1,2,3,4]+[6,7,8,9] #concatenation of lst
16.b=a[:] #cloning lst same as copy
17.a=lst() #to create a new empty lst

List comprehension

List comprehension represent creation of new lsit from an iterable object that satisfy given condition.

"""
syntax:
my_list=[expression dor item in iterable_object if object]
"""
list1=[i for i in range(10)]
list2=[i for i in range(20) if i%2==0 if i%3==0]
print(list1)
print(list2)
"""
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 6, 12, 18]
"""


"""
list compression with if else
syntax:
my_list=[expression if_statement else_statement for item in iterable_object]
"""
list3=[i if i%2==0 else "invalid" for i in range(20)]
print(list3)
"""
[0, 'invalid', 2, 'invalid', 4, 'invalid', 6, 'invalid', 8, 'invalid', 10, 'invalid', 12, 'invalid', 14, 'invalid', 16, 'invalid', 18, 'invalid']
"""


#nested list compression
lst=[[i*j for j in range(1,3)] for i in range(2,4)]
print(lst)
# for i in range(2,4):
#     for j in range(1,3):
#         pass

"""
[[2, 4], [3, 6]]
"""

 

iii.tuple

it contains the groups of the elements which ca be different type, it is similar to the list but tuplea sre read_only which means we cannoy modified it's elements. it is represents using the parenthesis().

#tuple
bio=("amrit",'engineer',23,5.5,True)
print(bio[1])
print(bio[-1])
# bio[3]=6.6   #modified is not possible in tuple
print(bio[3])

"""
engineer
True
5.5
"""

iv.range

it represnts the sequence of numbers. the numbers in the range are not modifiable.

rg1=range(5)
rg2=range(1,10,2)
print(rg1)
print(rg2)
print(rg1[3])

"""
range(0, 5)
range(1, 10, 2)
3
"""

 

4.sets

A sets is an unorders collections of the elements like a set in mathematics. orders in the set is not maintained , it means the elements may not appears in the same order as they are entered into the set. set are unordered so we can not access it's elements using the indexing. it us represents using the curly bracket {}.

set doesnot accepts duplicate elements.

#set
range(0, 5)
range(1, 10, 2)
3

"""
{True, 23, 5.5, 'amrit', 'engineer'}
"""

#set manipulation
a={1,2,3}
b={3,4,5}
1.set() #creating empty set
2.a.add(5) # to add new element
"""
we can add multiple element in set using update() method. update() method can take tuples,list,sting or other set as arguments.
"""
3.a.update([6,7,8,9])
4.a.remove(element) or a.discord(element)
5.b=a.copy()
6.a.clear()
7.a.intersection(b)
8.a.union(b)
9.a.difference(b)
10.a.issubset(b)
11.a.issuperset(b)

 

5.Mapping/dict/Dictionary

A map represents the group sof the elements in the fprm of key value pair.

#dictionary
cricket_player={1:"Parash",2:"Gayandra",3:"Sandeep",4:"Rohit",5:"karan"}
print(cricket_player[3])


"""
Sandeep
"""
god={
    1:"shiva",
    2:"ram",
    3:"krishna",
    4:"bhuddha"
}
1.god[1]
2.god[5]="hanuman" #add new
3.del god[4]
4.3 in god
5.new_god=god.copy()
6.god.clear()
7.formkeys()
"""
this method is used to create a new dictionay with specified key and value
key=(1,2,3)
value=("one","two","three")
new_dict=dict.fromkeys(key,value)
"""
8.god.get(1) # return value from specified key
9.god.items()
"""
this method return an object that contains key-value pair of dictionary as tuple
"""
10.god.keys() # return all keys , you can convert it into list using list(god.keys)
11.god.values()
12.god.update({key:value})
13.god.pop(key,defaultvalue(optional)) # remove the item with specified key
14.god.popitem()#remove the last inserted item,return remove item in tuple
15.god.setdefault(key,value)
"""
return the value of specidic key, if key is not found then it insert key with specified value
example:
god.setdefault(10,"sita")
"""
16. for accessing the ValueError
for k in god:
    print(k) # return key
    print(god[k]) # return value

for key,value in god.items():
    print(key,value)

Dictionary comhension

#dictionary comprehension
dict1={n:n*2 for n in range(10)}
dict2={n:n*2 for n in range(10) if n%2==0}
# if else 
dict3={n:(n if n%2==0 else "invalid") for n in range(10)}
print(dict1)
print(dict2)
print(dict3)

"""
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
{0: 0, 2: 4, 4: 8, 6: 12, 8: 16}
{0: 0, 1: 'invalid', 2: 2, 3: 'invalid', 4: 4, 5: 'invalid', 6: 6, 7: 'invalid', 8: 8, 9: 'invalid'}
"""

 

Note:

To know the type of datatype you can used the type() function.

country="Nepal"
land_area=147181 
area=1, 47, 181 
empty=''
district=['kavre','laltipur','bhaktapur']
zone=('bagmati','mahikali')
sports={"cricket","football",'vollerball','TT'}
cricket_player={1:"Parash",2:"Gayandra",3:"Sandeep",4:"Rohit",5:"karan"}

print(type(country))
print(type(land_area))
print(type(area))
print(type(empty))
print(type(district))
print(type(zone))
print(type(sports))
print(type(cricket_player))

"""
<class 'str'>
<class 'int'>
<class 'tuple'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
"""

 

Type Conversion In Python

Converting the one data type into another is called as type conversion.

Type of type conversion

1.Implicit Type Conversion

In implicit, python automatically convert the one data type into another .

#implicit type conversion

#example-1
a=5
b=2
print(a/b) # python convert into float value

#example-2
x="ne"
y="pal"
print(x+y)

# example-3
a=10
b=5.5
print(a-b) #python convert into float

"""
2.5
nepal
4.5
"""

2.Explicit Type Conversion

Programmer  convert the one data type into another .

eg:int(),float() and many more

#explicit type conversion
a=12345
b=20.00
print(int(b))
print(str(a))
print(complex(a))
print(bin(a))
print(oct(a))
print(hex(a))
print(float(a))
"""
20
12345
(12345+0j)
0b11000000111001
0o30071
0x3039
12345.0
"""

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

Amanda Martines 5 days ago

Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.

Reply

Baltej Singh 5 days ago

Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Marie Johnson 5 days ago

Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Leave a Reply

Scroll to Top