Python Data Types

Introduction

 
Data types are a term of classification types of data for a language. Python contains all the data types of lower-level language such as int, float, string, Boolean and also contains some advanced data types like a dictionary, tuples, list. Each variable contains a data type. Variable are nothing but reserved memory to store the value. Accordingly data types interpreter allocate the memory and decide which value can be stored in allocated memory. In the same variable, we can store multiple data types value but each size and location for stored memory space is changed.
 
In this part of the Python programming tutorial, we will talk about Python data types. Python has the following 6 standard data types.
  • Boolean
  • Numeric
  • String
  • List
  • Tuples
  • Dictionary
  • Sets
Now let's take some examples for each data type and understand their behavior.
 
Boolean
 
Boolean data types are similar to a coin. At a time either we found head or tail, such that Boolean either return True or False. There are two constants, true and false, these constants are used to assign the value to a Boolean data type.
 
Example 1:
 
Bool=True
 
Bool
 
Output:
 
True
 
Example 2:
  1. A=True;  
  2. B=False;  
  3. A&B ;  
  4. A|B;  
Output:
 
False
 
True
 
ENDING of True and False always returns false and ORING of True and False always return True.
 
Example 3:
 
print(True+False+True)
 
Output:
 
2
 
Python treats a True value as 1 and a False value as 0. So the above example returns 2(1+0+1).
 
Example 4:
  1. Bol=True;  
  2. if (Bol):  
  3.     print ("We Won the Match")  
  4. else:  
  5.     print ("We Lost the Match")  
Output:
 
We Won the Match
 
Example 5:
  1. ab=True;  
  2. print(type(ab));  
Output:
 
<class 'bool'>
 
Boolean data type belongs to the ‘bool’ class.
 
Example 6:
  1. print (bool(True));  
  2. print (bool(False));  
  3. print (bool(0));  
  4. print (bool());  
  5. print (bool(3))  
  6. print (bool("Pankaj"));  
  7. print (bool(""));  
  8. print (bool(' '));  
  9. print (bool(True+True));  
  10. print (bool(False+False));  
  11. print (bool(True+False));  
  12. print (bool(None));  
Output:
 
True
 
False
 
False
 
False
 
True
 
True
 
False
 
True
 
True
 
False
 
True
 
False
 
Numbers:
 
Numbers data types are used to store the numeric data. Python programming language contains an integer, floating-point, and complex numerical data types.
 
Example 1:
  1. Int_=12;  
  2. Float_=12.12;  
  3. Complex_=12+12j;  
  4. print(type(Int_)); #Integer data type  
  5. print(type(Float_)); # Floating Point Data type  
  6. print(type(Complex_)); # complex data typeOutput:  
Output:
 
<class 'int'>
 
<class 'float'>
 
<class 'complex'>
 
The above example shows that the integer data type belongs to “int” class, floating-point data type belong to “float” class and Complex data type belongs to “complex” class.
 
Example 2:
 
This example shows the different format for an integer data type.
  1. Dec_=12; #Decimal Format  
  2. Oct_=0o12; #Octal Format  
  3. Hex_=0x123; #Hexa-Deciaml Format  
  4. print(Dec_);  
  5. print(Oct_);  
  6. print(Hex_);  
Output:
 
12
 
10
 
291
 
Example 3:
 
This example shows various ways to represent a floating-point data type.
  1. Float1=12.12;  
  2. Float2=-12.12;  
  3. Float3=32E+8;  
  4. Float4=90;  
  5. Float5=12.4E-12;  
  6. print(Float1);  
  7. print(Float2);  
  8. print(Float3);  
  9. print(Float4);  
  10. print(Float5);  
Output:
 
12.12
 
-12.12
 
3200000000.0
 
90
 
1.24e-11
 
Example 4:
 
This example shows various ways to represent a complex data type.
  1. Comp1=10+11J;  
  2. Comp2=12-10J;  
  3. Comp3=-11-12J;  
  4. Comp4=90J;  
  5. Comp5=12.4E+10-12J;  
  6. Comp6=12.4E10-12J;  
  7. Comp7=complex(17,34);  
  8. Comp8=complex(23,-13);  
  9. print(Comp1);  
  10. print(Comp2);  
  11. print(Comp3);  
  12. print(Comp4);  
  13. print(Comp5);  
  14. print(Comp6);  
  15. print(Comp7);  
  16. print("Sum is=",(Comp7+Comp8));  
Output:
 
(10+11j)
 
(12-10j)
 
(-11-12j)
 
90j
 
(124000000000-12j)
 
(124000000000-12j)
 
(17+34j)
 
Sum is= (40+21j)
 
Strings:
 
Strings are data types that represents the textual data. String identified as a contiguous set of characters in between quotation marks.
 
Example 1:
  1. Str1='C#-Corner' #Single Quotes String  
  2. Str2="C#-Corner" #Double Quotes String  
  3. Str3="""C#-Corner""" #Triple Quotes String  
  4. print(Str1);  
  5. print(Str2);  
  6. print(Str3);  
Output:
 
C#-Corner
 
C#-Corner
 
C#-Corner
 
Example 2:
  1. Str="I Like Python"  
  2. print(Str); #Print Complete String  
  3. print(Str[0]); #Print First character  
  4. print(Str[1:7]); #Print Sub String from 2nd to 7th  
  5. print(Str[3:]) #Print Sub String from 4th to last   
  6. print(Str[:6]) #Print Sub String from first to 6th   
  7. print(Str[3:7]*3) #Print Sub String 3 times  
  8. print(Str[1:4]+Str[5:]) #Print Concatenation of String  
  9. print("I Like" " Python") #print Concatenation of String  
Output:
 
I Like Python
 
I
 
Like
 
ike Python
 
I Like
 
ike ike ike
 
Lie Python
 
I Like Python
 
Lists:
 
The list is similar to array data type of c and c++ language, but one difference that array always contains an item of same data types, but the list may have items of a different data type. The list data type is used to store a number of items. The list may store all the items of the same data type or compound data types. Items of a list are separated by comma(,) and enclosed within square brackets. The list is a mutable sequence and modifiable data type.
 
Example 1:
  1. List_=['Pankaj',21,'Alwar',21000.50,True]  
  2. print(List_) #Print All Item  
  3. print(List_[0]) #Print First Item  
  4. print(List_[1:5]) #Print from 2nd to 5th Item  
  5. print(List_[3:]) #Print from 4th to Last Item  
  6. print(List_[:2]) #Print 1st to 2nd Item   
  7. print(List_[1:3]*2) #Print Item two Times  
  8. print(List_[0:2]+List_[2:]) #Concatenate List  
Output:
 
['Pankaj', 21, 'Alwar', 21000.5, True]
 
Pankaj
 
[21, 'Alwar', 21000.5, True]
 
[21000.5, True]
 
['Pankaj', 21]
 
[21, 'Alwar', 21, 'Alwar']
 
['Pankaj', 21, 'Alwar', 21000.5, True]
 
Example 2:
 
We can sort the elements of a list.
  1. List_=[12,8,13,9,7,6,8];  
  2. List_.sort();  
  3. print(List_);  
Output:
 
[6, 7, 8, 8, 9, 12, 13]
 
Example 3:
 
The reverse() method arranges the item of an array in reverse order.
  1. List_=[12,8,13,9,7,6,8];  
  2. List_.reverse();  
  3. print(List_);  
Output:
 
[8, 6, 7, 9, 13, 8, 12]
 
Example 4:
 
The index method returns the index number of an item in the list. If the item does not exist in the list, then we will get an error.
  1. List_=[12,8,13,9,7,6,8]  
  2. print(List_.index(13));  
  3. print(List_.index(9));  
  4. print(List_.index(6));  
Output:
 
2
 
3
 
5
 
Example 5:
 
The count() method returns the frequency of an item in the list.
  1. List_=[12,8,12,11,8,12,11,8]  
  2. print(List_.count(8));  
  3. print(List_.count(12));  
  4. print(List_.count(11));  
Output:
 
3
 
3
 
2
 
Example 6:
  1. List_=[10,11,12];  
  2. print(List_);  
  3. #Append Method Insert a new Item in Consecutive Way  
  4. List_.append(13);  
  5. List_.append(14);  
  6. print(List_);  
  7. #Insert method Insert a Item at Given position  
  8. List_.insert(1,15);  
  9. List_.insert(4,16);  
  10. print(List_);  
  11. #remove method Delete a specific item from list  
  12. List_.remove(12);  
  13. List_.remove(14);  
  14. print(List_);  
  15. #DEL Keyword Delete Item of Specific Position  
  16. del List_[1];  
  17. del List_[3];  
  18. print(List_);  
Output:
 
[10, 11, 12]
 
[10, 11, 12, 13, 14]
 
[10, 15, 11, 12, 16, 13, 14]
 
[10, 15, 11, 16, 13]
 
[10, 11, 16]
 
Tuples:
 
Tuples are also used to store multiple data items. These items may have the same or different data types. Tuples are an immutable sequence data type. Tuples contain items separated by a comma and closed by parentheses. Tuples are similar to read-only lists.
 
There is two major difference between List and Tuples:
  • A list item is enclosed by brackets and Tuples items are closed by parentheses.
     
  • The list can be updated but Tuples can’t be updated.
Example 1:
  1. Tuple_=("Pankaj",10,12.12,True,"Alwar",25000)  
  2. print(Tuple_); #Print All Item  
  3. print(Tuple_[2]); #Print 3rd Item  
  4. print(Tuple_[1:3]); #Print Item from 2nd to 3rd Item  
  5. print(Tuple_[2:]); #Print item from 3rd to Last item  
  6. print(Tuple_[:4]); #Print 1st to 4th Item  
  7. print(Tuple_[0:2]+Tuple_[2:]) #Concatenate Two Tuples  
  8. print(Tuple_[2:5]*2) #Print Item two times  
Output:
 
('Pankaj', 10, 12.12, True, 'Alwar', 25000)
 
12.12
 
(10, 12.12)
 
(12.12, True, 'Alwar', 25000)
 
('Pankaj', 10, 12.12, True)
 
('Pankaj', 10, 12.12, True, 'Alwar', 25000)
 
(12.12, True, 'Alwar', 12.12, True, 'Alwar')
 
Example 2:
  1. Tuple_=(10,12,16,13,19,18)  
  2. print(len(Tuple_)); #Print Length  
  3. print(max(Tuple_)); #Print Max Item  
  4. print(min(Tuple_)); #Print Min Item  
  5. print(Tuple_[-1]) #Print Last Item  
  6. print(Tuple_[-2]); #Print Second Item from End  
Output:
 
6
 
19
 
10
 
18
 
19
 
Example 3:
 
Python programming allows us to create nested Tuples.
 
Nested Tuples
  1. Tuple_=(10,(12,16,13),(19,18,22),(27,35,42));  
  2. print(len(Tuple_));  
  3. print(Tuple_[1]);  
  4. print(Tuple_[1][2]);  
  5. print(Tuple_[2][1]);  
  6. print(Tuple_[3][1:]);  
  7. print(Tuple_[3][1:2]);  
  8. print(Tuple_[1]+Tuple_[2]);  
  9. print(max(Tuple_[1]));  
  10. print(min(Tuple_[2]));  
Output:
 
4
 
(12, 16, 13)
 
13
 
18
 
(35, 42)
 
(35,)
 
(12, 16, 13, 19, 18, 22)
 
16
 
18
 
Example 4:
  1. Tuple_=(10,(12,16,13),(19,18,22),(27,35,42));  
  2. Tuple_[0]=12;  
Output:
 
Traceback (most recent call last):
 
File "<pyshell#178>", line 1, in <module>
 
Tuple_[0]=12
 
TypeError: 'tuple' object does not support item assignment
 
When we execute the above code, we find an error because Tuples are immutable in nature, so we can’t modify a Tuple.
 
Dictionary:
 
Python dictionaries are kind of hash table type. Dictionary is a group of key-value pairs and items of a dictionary are indexed by keys. A key is a dictionary that must be unique. Dictionary works like an associative array. Dictionary items are enclosed by curly braces( {}) and items are accessed and assigned by brackets([]).
 
Example 1:
  1. Dict={"Name":"Pankaj choudhary""Class":12,"Age":21};  
  2. Dict["Married"]=False; #Add New Item  
  3. Dict["Salary"]=25000.50; #Add New Item  
  4. print(Dict);  
  5. print(Dict["Name"]); #Print Value for "Name" Key  
  6. print(Dict["Age"]); #Print Value for "Age" Key  
  7. print(Dict.keys()); #Print All Keys  
  8. print(Dict.values()); #Print All Values  
  9. print(Dict.items()); #Print Key Value Pair  
  10. Dict.pop("Age"); #Remove "Age" Key Item  
  11. print(Dict);  
  12. Dict.clear(); #Clear Dictionary  
  13. print(Dict);  
Output:
 
{'Age': 21, 'Name': 'Pankaj choudhary', 'Married': False, 'Class': 12, 'Salary': 25000.5}
 
Pankaj choudhary
 
21
 
dict_keys(['Age', 'Name', 'Married', 'Class', 'Salary'])
 
dict_values([21, 'Pankaj choudhary', False, 12, 25000.5])
 
dict_items([('Age', 21), ('Name', 'Pankaj choudhary'), ('Married', False), ('Class', 12), ('Salary',
 
25000.5)])
 
{'Name': 'Pankaj choudhary', 'Married': False, 'Class': 12, 'Salary': 25000.5}
 
{}
 
None:
 
None is a special data type that represents the non-existence of data. A None data type is also used for empty or unknown data.
 
Example:
  1. Non=None;  
  2. print(Non);  
Output:
 
None
 
Sets:
 
Sets are unordered data types that represent a collection of data and used for performing set operations such as intersection, union, differences, etc.
 
Example 1:
  1. Set1=set([10,15,11,13,18,21,27,14,28,29]); #Create Set  
  2. Set2=set([11,18,21,13]); #Create Set  
  3. Set1.add(17); #Add Item   
  4. Set1.add(19); #Add Item   
  5. Set1.add(22); #Add Item   
  6. Set2.add(15); #Add Item   
  7. Set2.add(27); #Add Item   
  8. Set2.add(14); #Add Item   
  9. print(Set1);  
  10. print(Set2);  
  11. print(Set1|Set2) #Union  
  12. print(Set1&Set2) #Intersection  
  13. print(Set1-Set2) #Difference   
  14. print(Set1^Set2); #Symmetric Difference  
  15. Set1.remove(10); #Remove Item  
  16. Set2.remove(13); #Remove Item  
  17. print(Set1);  
  18. print(Set2);  
  19. print(Set2.issuperset(Set1)); #Check that Set2 is Superset of Set1 or Not   
  20. print(Set2.issubset(Set1)); #Check that Set2 is Subset of Set1 or Not  
  21. Set1.clear(); #Clear Set  
  22. Set2.clear(); #Clear Set  
  23. print(Set1);  
  24. print(Set2);  
Output:
 
{10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 27, 28, 29}
 
{11, 13, 14, 15, 18, 21, 27}
 
{10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 27, 28, 29}
 
{11, 13, 14, 15, 18, 21, 27}
 
{10, 17, 19, 22, 28, 29}
 
{10, 17, 19, 22, 28, 29}
 
{11, 13, 14, 15, 17, 18, 19, 21, 22, 27, 28, 29}
 
{11, 14, 15, 18, 21, 27}
 
False
 
True
 
set()
 
set()
 
Conversion Function:
 
The conversion function is used to perform a conversion between the built-in data types. Python contains several built-in conversion functions as follows.
 
Int(x,base=y)
 
The int function converts the string x into an integer value of the specific base.
 
Example:
  1. print(int('100',base=10));  
  2. print(int('100',base=8));  
  3. print(int('100',base=16));  
  4. print(int('100',base=20));  
  5. print(int('100',base=15)); 
Output:
 
100
 
64
 
256
 
400
 
225
 
Float(x):
 
The float function converts the string into a floating-point number.
 
Example :
  1. print(float('12.12'));  
  2. print(float('-12.12'));  
  3. print(float('12345'));  
  4. print(float('12E+12'));  
  5. print(float('12E-12'));  
Output:
 
12.12
 
-12.12
 
12345.0
 
12000000000000.0
 
1.2e-11
 
Oct(x) :
 
The oct(x) function convert the integer value into octal string.
 
Example:
  1. print(oct(12));  
  2. print(oct(-12));  
  3. print(oct(120));  
Output:
 
0o14
 
-0o14
 
0o170
 
Hex(x) :
 
The hex(x) function convert the integer value to hexadecimal string.
 
Example:
  1. print(hex(12));  
  2. print(hex(-12));  
  3. print(hex(120));  
Output:
 
0xc
 
-0xc
 
0x78
 
Ord(x) :
 
The ord(x) convert the single character to it’s integer value.
 
Example:
  1. print(ord('a'));  
  2. print(ord('A'));  
  3. print(ord('z'));  
  4. print(ord('Z'));  
Output:
 
97
 
65
 
122
 
90
 
Chr(x) :
 
The chr(x) function convert the integer value to a character.
 
Example:
  1. print(chr(126));  
  2. print(chr(100));  
  3. print(chr(54));  
  4. print(chr(78));  
Output:
 
}
 
d
 
6
 
N
 
Complex(real,imag) :
 
The complex(real,imag) function is used to create a complex number.
 
Example:
  1. print(complex(10,11));  
  2. print(complex(-10,11));  
  3. print(complex(10,-11));  
  4. print(complex(-10,-11));  
  5. print(complex(0,11));  
  6. print(complex(10,0));  
Output:
 
(10+11j)
 
(-10+11j)
 
(10-11j)
 
(-10-11j)
 
11j
 
(10+0j)
 
List(x):
 
The list function(x) function is used to convert a string or tuple to a list.
 
Example:
  1. Str='12345';  
  2. Tup_=(123,'Pankaj',12.12,250);  
  3. print(list(Str));  
  4. print(list(Tup_));  
Output:
 
['1', '2', '3', '4', '5']
 
[123, 'Pankaj', 12.12, 250]
 
Tuple(x) :
 
The tuple(x) function is used to convert a string or list to a tuple.
 
Example:
  1. Str='12345';  
  2. List_=[123,'Pankaj',12.12,250];  
  3. print(tuple(Str));  
  4. print(tuple(List_));  
Output:
 
('1', '2', '3', '4', '5')
 
(123, 'Pankaj', 12.12, 250)
 
Set(x) :
 
The set(x) function convert a string or list to set data type.
 
Example:
  1. Str='12345';  
  2. List_=[123,'Pankaj',12.12,250];  
  3. print(set(Str));  
  4. print(set(List_));  
Output:
 
{'3', '4', '5', '1', '2'}
 
{250, 123, 12.12, 'Pankaj'}
 
Dict(x) :
 
The dict(x) function is used to convert the sequence of key-value tuples to dictionary.
 
Example:
  1. Tupl={"Name":"Pankaj Kumar Choudhary","Age":20,"Salary":25000,"Married":False}  
  2. print(dict(Tupl));  
  3. print(dict(Tupl).items());  
Output:
 
{'Age': 20, 'Salary': 25000, 'Married': False, 'Name': 'Pankaj Kumar Choudhary'}
 
dict_items([('Age', 20), ('Salary', 25000), ('Married', False), ('Name', 'Pankaj Kumar Choudhary')])
 
Point to Consider:
 
Point1
 
If we assign multiple variables to the same object then each variable will contain the same reference.
 
Example:
 
 
Point 2:
 
Number and string are immutable data types. It means if we change the value of number or string data type then a new variable will generate and store to another memory location.
 
Example:
 
 
Today we learned data types and some conversion functions in python. I hope you liked this article.
 
Thanks for reading the article.


Recommended Free Ebook
Similar Articles