Data Types In Python

data_type
 

Python Data Types

 
Every value in Python has a datatype. Since everything is an object in Python programming, data types are classes and variables are instance (object) of these classes.
 
We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a class.
 
The common data types in python are Python Numbers, Python List, Python Tuple, Python Strings, Python Set, and Python Dictionary. In this article, we will see these data types with code examples.
 

Python Numbers

 
Python Numbers data types store numeric values. Integers, floating-point numbers, and complex numbers come under the Python numbers category. Integer type holds all the positive and negative whole numbers of any length, for example, 1234567890123456789, -100. Float type holds the real numbers and is represented by a decimal.
 
Floating-point numbers are accurate up to 15 decimal places (the 16th place is inaccurate) because Python built-in class float performs some calculations that might amaze us.
 
In Python 1.1 + 2.2 gives 3.3000000000000003 instead of 3.3 because floating-point numbers are implemented in computer hardware as binary fractions, as a computer only understands binary (0 and 1).
 
To overcome the above issue, we can use the decimal module that comes with Python. For example,
  1. from decimal import Decimal as D  
  2. print(D('1.1') + D('2.2')) gives Output: 3.3  
  3. print(D('1.1') + D('2.2') == D('3.3')) return True  
It is important to note that Floating-point operations are carried out must faster than Decimal operations. So, use Decimal only when exact decimal representation needed, to control the level of precision required,
  • Binary numbers can be represented by appropriately placing a prefix '0b' or '0B' for example, print(0b1101011) gives an Output: 107
  • Hexadecimal numbers can be represented by appropriately placing a prefix '0x' or '0X' for example, print(0xFB) gives an output 251
  • Octal numbers can be represented by appropriately placing a prefix '0o' or '0O' for example, print(0o15) gives an output 13
  • Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part, for example, z = 5 + 3j.
The real part can be accessed using the function real() for example
  1. z = 5 + 3j;  
  2. print ("The real part of complex number is: ", z.real) gives an output 5.0  
The imaginary part can be accessed using the function imag().
  1. z = 5 + 3j;  
  2. print ("The imaginary part of complex number is: ", z.imag) gives an output 3.0  

Python Lists

 
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. A single list may contain DataTypes like Integers, Strings, as well as Objects. The list is a container, which is used to store multiple data at the same time and items and is the first ordered index.
 
Lists in Python can be created by just placing the sequence inside the square brackets[] for example
  1. List = ["12","random"] where List is the name of the variable  
  2. List2 = ["13", "random"] where List2 is the name of the list initialized and this is different from List.   
A list may contain duplicate values with their distinct positions
  1. List = ["12","random","12"]  
Multi-Dimensional List can be created by Nesting a list inside a List for example:
  1. List = [['Python''For'] , ['Techs']]  
  2. print(List[0]) return ['Python''For']  
  3. print(List[0][0]) return ['Python']  
  4. print(List[0][1]) return ['For']   
Elements can be added to the List by using built-in append() function for example:
  1. List = ["12","random"]  
  2. List.append(24);  
  3. Print(List) returns ["12","random""24"]   
Elements can be added to the specific Position in the List by using Insert Method for example:
  1. List = ["12","random","group"]  
  2. List.insert(222) will return ["12","random","22","group"]  
Use the index operator [] to access an item in a list, for example:
  1. List = ['For', ['Geeks']]  
  2. print(List[0]) return ['For']  
Use Remove() method to remove one element from the list at a time for example:
  1. List = ["12","13","14"]  
  2. List.remove(13) will remove 13 from the list  
Remove() method raise error if the element does not exists in the list. To avoid or handle, we can check the existence of element in the list.
  1. If 13 in List: List.remove(13)   
Use Pop() method to remove the first element and pass index if want to remove a specific element from the list for example:
  1. List = ["12","13","14"]  
  2. List.pop() will remove 14 from the list  
  3. List.pop(2) will remove 14 from the list  
Python allows negative indexing for its list. The index of -1 refers to the last item, -2 to the second last item and so on.
 
Python expression list[listelements]*N will return list with elements added N times to the original list if N is the positive number whereas output will be an empty list if N is a negative integer or 0.
 
Slicing of List items is about printing or extracting a range of elements from the list.
 
Slice operation is performed on Lists with the use of a colon(:).
 
Print elements of a range using Slice operation.
  1. List = ['G','E','E','K','S','F''O','R','G','E','S']  
  2. Sliced_List = List[3:8] will return ['K''S''F''O''R']  
  3. Sliced_List = List[:8] will return elements starting first till 8th element ['G','E','E','K','S','F''O','R']  
  4. Sliced_List = List[3:-6] will return elements ['K','S'] which means slice first two element from start and 6 elements from the end  
Slicing can also be done by using the syntax listName[x:y:z] where x means the initial index, y-1 defines the final index value and z specifies the step size. If any one of the values among x, y and z is missing the interpreter takes default value
  1. list = ['python''learning''@''Geeks''for''Geeks']  
  2. print list[0:6:2] will return ['python''@''for']   

Python Tuples

 
Tuple is a sequence of heterogeneous elements (can contain data of any type like integers, string, etc.,) syntactically separated by 'commas' closed in parentheses.
 
To make a tuple, there must be a trailing 'comma' if there is only one element or value.
 
List can be converted to a Tuple by using in built function, for example,
  1. list1 = [12456]  
  2. Tuple1 = tuple(list1)  
  3. print(Tuple1) will return (12456)  
Tuple can be nested into the other tuple
  1. Tuple1 = (0123)  
  2. Tuple2 = ('python''course')  
  3. Tuple3 = (Tuple1, Tuple2)  
  4. print("\nTuple with nested tuples: ")  
  5. print(Tuple3) will return (('python''course') ,(Tuple1, Tuple2))   
Concatenation of tuple is the process of joining of two or more Tuples using '+' operator
  1. Tuple1 = (0123)  
  2. Tuple2 = ('Python''For''Techs')  
  3. Tuple3 = Tuple1 + Tuple2  
  4. print(Tuple3) will return (0123'Python''For''Techs')  
'*' operator is used to add the elements repetitively into the tuple .
 
Sorted operation takes input elements in the tuple and return a new sorted list for example,
  1. tuple11 = (9,2,7,4,1)  
  2. print((sorted(tuple11)) will return [1,2,4,7,9
The statement tuple('python') will unpack the string into the characters which means this statement will become or treated as tuple(p, y, t, h, o, n) 
 
Tuples are immutable and don't have an append method. 
 
Slice operation is performed on Tuple and is similar to List with the use of colon(:)
  1. tuple11 = (9,2,7,4,1,56,23,11,45)  
  2. print(tuple11[4:6]) will return (1,56,23)  
  3. print(tuple11[-4:]) will return (56,23,11,45)  
A comparison of two tuples starts with the first element of each tuple. If they do not compare to =, < or > then it proceeds to the second element and so on for example
  1. a=(5,6and b=(1,4) here a is bigger than b because the first element of tuple a is bigger than b  
  2. a=(5,4and b= (5,6) here b is bigger than a because the first element of tuple a and b is same but second of tuple b is bigger than a  

Python Set

 
Set is an unordered, unindexed collection data type that is mutable, syntactically separated by 'commas' closed in curly braces and has no duplicate elements for example:
  1. Set1 = {"1", "2", "3"}  
It ignores duplicate elements automatically and return only unique elements for example:
  1. setunique = {"1", "2", "3", "3"} will return {"1", "2", "3"}  
Elements of set cannot be accessed using index.
 
Use add() method to add one item Or use method update() to add multiple items into the set.
 
Add method does not return any value.
 
Set does not support operator "+" which means concatenation of two sets is not possible.
 
Copy() method creates a copy of sets, changes to the copy do not reflect or make changes to the original set to remove an element in a set, either use discard() or remove() method.
 
discard() method does not raise any error when element is not present in the set whereas remove() method raise an error.
 
pop() is another method that can be used to remove the element but you will not know which item gets removed because set is an unordered collection.
 
difference() returns the difference of two or more sets as a new set for example:
  1. x = {"apple""banana""cherry"}  
  2. y = {"apple""cherry"}  
  3. z= x.difference(y) means z will be a new set and will contain "banana" 
difference_update() removes the elements of second set from the first set and it does not return new.
 
union() is the method used to concatenate two sets which will remove duplicates.
 
intersection() is the method that returns a set with all the elements which are contained in both sets.
 

Python Dictionary

 
Dictionary is an unordered collection of data values, stored as key-value pairs where key and value are separated by ":" colon.
 
Key must be unique and can be of any data type such as Strings, Integers, and tuples. Duplicate keys are not allowed in python. If there are matching keys in a dictionary, then the value assigned mostly recently is assigned to that key.
 
Key names are case-sensitive which means the same name with a different case will be treated distinctly.
 
Dictionary can be created by placing key:value pair enclosed within the curly braces for example:
  1. Dictionary = {1: "Python" 2: "Learning", 3: "Course"}   
One dictionary object can be nested inside another dictionary:
  1. NestedDictionary = {1: "Python Data Type" 2: "{1: "Integer", 2: "String", 3: "Complex"}"}   
Dictionary items can be accessed by specifying the key name inside square brackets
  1. Dictionary = {1: "Python" 2: "Learning", 3: "Course"}  
  2. Print(Dictionary[1]) will return Python  
Item can be added to dictionary by defining value along with the key e.g. Dict[Key] = 'Value'.
 
In a similar way, existing dictionary item can be updated by defining value along with the key e.g. Dict[Key] = 'Value' otherwise it will add a new item into the dictionary,
  • the pop() method can be used to remove or delete the specific item from the dictionary. The pop method accept the key as a parameter. Pop method raises an error if the specified key does not exist
  • popitem() method can be used to delete the first element of a dictionary
  • kas_Key() method can be used to validate if a key exists in the dictionary or not
  • values() return collection of values stored in the dictionary
  • keys() return collection of keys stored in the dictionary
  • fromkeys() create a new dictionary with keys from a list given to it as an argument and set values of the key, the default value given in it as an argument.

Python String

 
Strings are arrays of bytes representing Unicode characters.
 
The string can be created using single quotes or double quotes or even triple quotes.
 
Using triple quotes is preferred way as it helps in creation of Strings with single and double quotes in them for example,
  1. String1 = '''''I'm a Geek and I live in a world of "Geeks"'''  
  2. Print(String1) return I'm a Geek and I live in a world of "Geeks"  
Individual characters of a String can be accessed by using the method of Indexing. 0 index returns first character whereas negative index returns characters from the end like -1 returns first character from the end (last character of the string).
  1. stringPython = "PythonProgrammers"  
  2. print(stringPython[0]) return 'P'  
  3. print(stringPython[-1]) return 's'   
A range of characters in the String can be accessed by using the slicing operator.
  1. stringPython = "PythonProgrammers"  
  2. print(stringPython[0:6]) return 'Python'  
  3. print(stringPython[6:-1]) return 'Programmer'  
Strings are immutable, hence updating or deleting characters from a String is not allowed but updating or deleting the entire string is possible.
 
Format() method can be used to format string. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order for example,
  1. stringFormatted = "{1} {0} {2}".format('Python''For''Programmers')  
  2. print(stringFormatted) return 'For Python Programmers'   

Conclusion

 
In this article we discussed data types including Numbers, Tuples, List, Set, Dictionary, and String supported in Python.