Introduction
Data types is a term of classification types of data for a language. Python contain all the data types of lower level language such as int, float, string, Boolean and also contain some advanced data types like 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 that which value can be stored in allocated memory. In 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:
- A=True;
- B=False;
- A&B ;
- A|B;
Output:
False
True
ENDING of True and False always return 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 above example return 2(1+0+1).
Example 4:- Bol=True;
- if (Bol):
- print ("We Won the Match")
- else:
- print ("We Lost the Match")
Output:
We Won the Match
Example 5:- ab=True;
- print(type(ab));
Output: <class 'bool'>
Boolean data type belong to ‘bool’ class.
Example 6:- print (bool(True));
- print (bool(False));
- print (bool(0));
- print (bool());
- print (bool(3))
- print (bool("Pankaj"));
- print (bool(""));
- print (bool(' '));
- print (bool(True+True));
- print (bool(False+False));
- print (bool(True+False));
- print (bool(None));
Output:
True
False
False
False
True
True
False
True
True
False
True
False
Numbers:
Numbers data type are used to store the numeric data. Python programming language contain integer, floating point and complex numerical data types.
Example 1:- Int_=12;
- Float_=12.12;
- Complex_=12+12j;
- print(type(Int_)); #Integer data type
- print(type(Float_)); # Floating Point Data type
- print(type(Complex_)); # complex data typeOutput:
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Above example show that the integer data type belong to “int” class, floating point data type belong to “float” class and Complex data type belong to “complex” class.
Example 2: This example show the different format for integer data type.
- Dec_=12; #Decimal Format
- Oct_=0o12; #Octal Format
- Hex_=0x123; #Hexa-Deciaml Format
- print(Dec_);
- print(Oct_);
- print(Hex_);
Output: 12
10
291
Example 3: This example shows various ways to represent a floating point data type.
- Float1=12.12;
- Float2=-12.12;
- Float3=32E+8;
- Float4=90;
- Float5=12.4E-12;
- print(Float1);
- print(Float2);
- print(Float3);
- print(Float4);
- 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.
- Comp1=10+11J;
- Comp2=12-10J;
- Comp3=-11-12J;
- Comp4=90J;
- Comp5=12.4E+10-12J;
- Comp6=12.4E10-12J;
- Comp7=complex(17,34);
- Comp8=complex(23,-13);
- print(Comp1);
- print(Comp2);
- print(Comp3);
- print(Comp4);
- print(Comp5);
- print(Comp6);
- print(Comp7);
- 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 type that represent the textual data. String identified as a contiguous set of characters in between quotation marks.
Example 1:- Str1='C#-Corner' #Single Quotes String
- Str2="C#-Corner" #Double Quotes String
- Str3="""C#-Corner""" #Triple Quotes String
- print(Str1);
- print(Str2);
- print(Str3);
Output: C#-Corner
C#-Corner
C#-Corner
Example 2:- Str="I Like Python"
- print(Str); #Print Complete String
- print(Str[0]); #Print First character
- print(Str[1:7]); #Print Sub String from 2nd to 7th
- print(Str[3:]) #Print Sub String from 4th to last
- print(Str[:6]) #Print Sub String from first to 6th
- print(Str[3:7]*3) #Print Sub String 3 times
- print(Str[1:4]+Str[5:]) #Print Concatenation of String
- 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: List is similar to array data type of c and c++ language, but one difference that array always contain item of same data types, but list may have items of different data type. List data type is used to store a number of items. List may store all the items of same data type or compound data types. Items of a list are separated by comma(,) and enclosed within square brackets. List is a mutable sequence and modifiable data type.
Example 1:- List_=['Pankaj',21,'Alwar',21000.50,True]
- print(List_) #Print All Item
- print(List_[0]) #Print First Item
- print(List_[1:5]) #Print from 2nd to 5th Item
- print(List_[3:]) #Print from 4th to Last Item
- print(List_[:2]) #Print 1st to 2nd Item
- print(List_[1:3]*2) #Print Item two Times
- 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.
- List_=[12,8,13,9,7,6,8];
- List_.sort();
- print(List_);
Output:
[6, 7, 8, 8, 9, 12, 13]
Example 3:
The reverse() method arrange the item of array in reverse order.
- List_=[12,8,13,9,7,6,8];
- List_.reverse();
- print(List_);
Output:
[8, 6, 7, 9, 13, 8, 12]
Example 4:
The index method return the index number of a item in list. If item does not exist in list, then we will get an error.
- List_=[12,8,13,9,7,6,8]
- print(List_.index(13));
- print(List_.index(9));
- print(List_.index(6));
Output:
2
3
5
Example 5: The count() method return the frequency of an item in list.
- List_=[12,8,12,11,8,12,11,8]
- print(List_.count(8));
- print(List_.count(12));
- print(List_.count(11));
Output:
3
3
2
Example 6:- List_=[10,11,12];
- print(List_);
- #Append Method Insert a new Item in Consecutive Way
- List_.append(13);
- List_.append(14);
- print(List_);
- #Insert method Insert a Item at Given position
- List_.insert(1,15);
- List_.insert(4,16);
- print(List_);
- #remove method Delete a specific item from list
- List_.remove(12);
- List_.remove(14);
- print(List_);
- #DEL Keyword Delete Item of Specific Position
- del List_[1];
- del List_[3];
- 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 same or different data type . Tuples are an immutable sequence data type. Tuples contains item separated by comma and closed by parentheses. Tuples similar as read-only lists.
There are two major difference between List and Tuples:
- List item are enclosed by brackets and Tuples item are closed by parentheses.
- List can be updated but Tuples can’t be updated.
Example 1:
- Tuple_=("Pankaj",10,12.12,True,"Alwar",25000)
- print(Tuple_); #Print All Item
- print(Tuple_[2]); #Print 3rd Item
- print(Tuple_[1:3]); #Print Item from 2nd to 3rd Item
- print(Tuple_[2:]); #Print item from 3rd to Last item
- print(Tuple_[:4]); #Print 1st to 4th Item
- print(Tuple_[0:2]+Tuple_[2:]) #Concatenate Two Tuples
- 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:- Tuple_=(10,12,16,13,19,18)
- print(len(Tuple_)); #Print Length
- print(max(Tuple_)); #Print Max Item
- print(min(Tuple_)); #Print Min Item
- print(Tuple_[-1]) #Print Last Item
- print(Tuple_[-2]); #Print Second Item from End
Output:
6
19
10
18
19
Example 3:
Python programming allow us to create the nested Tuples.
Nested Tuples- Tuple_=(10,(12,16,13),(19,18,22),(27,35,42));
- print(len(Tuple_));
- print(Tuple_[1]);
- print(Tuple_[1][2]);
- print(Tuple_[2][1]);
- print(Tuple_[3][1:]);
- print(Tuple_[3][1:2]);
- print(Tuple_[1]+Tuple_[2]);
- print(max(Tuple_[1]));
- print(min(Tuple_[2]));
Output:
4
(12, 16, 13)
13
18
(35, 42)
(35,)
(12, 16, 13, 19, 18, 22)
16
18
Example 4:- Tuple_=(10,(12,16,13),(19,18,22),(27,35,42));
- 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 item of dictionary are indexed by keys. Key is a dictionary must be unique. Dictionary works like associative array. Dictionary items are enclosed by curly braces( {}) and items are accessed and assigned by brackets([]).
Example 1:- Dict={"Name":"Pankaj choudhary", "Class":12,"Age":21};
- Dict["Married"]=False; #Add New Item
- Dict["Salary"]=25000.50; #Add New Item
- print(Dict);
- print(Dict["Name"]); #Print Value for "Name" Key
- print(Dict["Age"]); #Print Value for "Age" Key
- print(Dict.keys()); #Print All Keys
- print(Dict.values()); #Print All Values
- print(Dict.items()); #Print Key Value Pair
- Dict.pop("Age"); #Remove "Age" Key Item
- print(Dict);
- Dict.clear(); #Clear Dictionary
- 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 represent non-existence of data. None data type is also used for empty or unknown data.
Example: Output:
None
Sets:
Sets are unordered data types that represent collection of data and used for performing set operations such as intersection, union, differences, etc.
Example 1:- Set1=set([10,15,11,13,18,21,27,14,28,29]); #Create Set
- Set2=set([11,18,21,13]); #Create Set
- Set1.add(17); #Add Item
- Set1.add(19); #Add Item
- Set1.add(22); #Add Item
- Set2.add(15); #Add Item
- Set2.add(27); #Add Item
- Set2.add(14); #Add Item
- print(Set1);
- print(Set2);
- print(Set1|Set2) #Union
- print(Set1&Set2) #Intersection
- print(Set1-Set2) #Difference
- print(Set1^Set2); #Symmetric Difference
- Set1.remove(10); #Remove Item
- Set2.remove(13); #Remove Item
- print(Set1);
- print(Set2);
- print(Set2.issuperset(Set1)); #Check that Set2 is Superset of Set1 or Not
- print(Set2.issubset(Set1)); #Check that Set2 is Subset of Set1 or Not
- Set1.clear(); #Clear Set
- Set2.clear(); #Clear Set
- print(Set1);
- 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:
Conversion function are used to perform conversion between the built-in data types. Python contain several built-in conversion function as follows.
Int(x,base=y)
The int function convert the string x into an integer value of specific base.
Example:- print(int('100',base=10));
- print(int('100',base=8));
- print(int('100',base=16));
- print(int('100',base=20));
- print(int('100',base=15));
Output:
100
64
256
400
225
Float(x):
The float function convert the string into floating point number.
Example :- print(float('12.12'));
- print(float('-12.12'));
- print(float('12345'));
- print(float('12E+12'));
- 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:- print(oct(12));
- print(oct(-12));
- print(oct(120));
Output:
0o14
-0o14
0o170
Hex(x) :
The hex(x) function convert the integer value to hexadecimal string.
Example:- print(hex(12));
- print(hex(-12));
- print(hex(120));
Output:
0xc
-0xc
0x78
Ord(x) :
The ord(x) convert the single character to it’s integer value.
Example:- print(ord('a'));
- print(ord('A'));
- print(ord('z'));
- print(ord('Z'));
Output:
97
65
122
90
Chr(x) :
The chr(x) function convert the integer value to a character.
Example:- print(chr(126));
- print(chr(100));
- print(chr(54));
- print(chr(78));
Output:
}
d
6
N
Complex(real,imag) :
The complex(real,imag) function is used to create a complex number.
Example:- print(complex(10,11));
- print(complex(-10,11));
- print(complex(10,-11));
- print(complex(-10,-11));
- print(complex(0,11));
- 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:- Str='12345';
- Tup_=(123,'Pankaj',12.12,250);
- print(list(Str));
- 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:- Str='12345';
- List_=[123,'Pankaj',12.12,250];
- print(tuple(Str));
- 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:- Str='12345';
- List_=[123,'Pankaj',12.12,250];
- print(set(Str));
- 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:- Tupl={"Name":"Pankaj Kumar Choudhary","Age":20,"Salary":25000,"Married":False}
- print(dict(Tupl));
- 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 variable to same object then each variable will contain 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.