
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
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).
- from decimal import Decimal as D
- print(D('1.1') + D('2.2')) gives Output: 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.
- z = 5 + 3j;
- print ("The real part of complex number is: ", z.real) gives an output 5.0
- z = 5 + 3j;
- 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.
- List = ["12","random"] where List is the name of the variable
- List2 = ["13", "random"] where List2 is the name of the list initialized and this is different from List.
- List = ["12","random","12"]
- List = [['Python', 'For'] , ['Techs']]
- print(List[0]) return ['Python', 'For']
- print(List[0][0]) return ['Python']
- print(List[0][1]) return ['For']
- List = ["12","random"]
- List.append(24);
- Print(List) returns ["12","random", "24"]
- List = ["12","random","group"]
- List.insert(2, 22) will return ["12","random","22","group"]
- List = ['For', ['Geeks']]
- print(List[0]) return ['For']
- List = ["12","13","14"]
- List.remove(13) will remove 13 from the list
- If 13 in List: List.remove(13)
- List = ["12","13","14"]
- List.pop() will remove 14 from the list
- 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(:).
- List = ['G','E','E','K','S','F', 'O','R','G','E','S']
- Sliced_List = List[3:8] will return ['K', 'S', 'F', 'O', 'R']
- Sliced_List = List[:8] will return elements starting first till 8th element ['G','E','E','K','S','F', 'O','R']
- Sliced_List = List[3:-6] will return elements ['K','S'] which means slice first two element from start and 6 elements from the end
- list = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
- 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.
- list1 = [1, 2, 4, 5, 6]
- Tuple1 = tuple(list1)
- print(Tuple1) will return (1, 2, 4, 5, 6)
- Tuple1 = (0, 1, 2, 3)
- Tuple2 = ('python', 'course')
- Tuple3 = (Tuple1, Tuple2)
- print("\nTuple with nested tuples: ")
- print(Tuple3) will return (('python', 'course') ,(Tuple1, Tuple2))
- Tuple1 = (0, 1, 2, 3)
- Tuple2 = ('Python', 'For', 'Techs')
- Tuple3 = Tuple1 + Tuple2
- print(Tuple3) will return (0, 1, 2, 3, 'Python', 'For', 'Techs')
'*' operator is used to add the elements repetitively into the tuple .
- tuple11 = (9,2,7,4,1)
- 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.
- tuple11 = (9,2,7,4,1,56,23,11,45)
- print(tuple11[4:6]) will return (1,56,23)
- print(tuple11[-4:]) will return (56,23,11,45)
- a=(5,6) and b=(1,4) here a is bigger than b because the first element of tuple a is bigger than b
- a=(5,4) and 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
- Set1 = {"1", "2", "3"}
- 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.
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:
- x = {"apple", "banana", "cherry"}
- y = {"apple", "cherry"}
- 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 = {1: "Python" 2: "Learning", 3: "Course"}
- NestedDictionary = {1: "Python Data Type" 2: "{1: "Integer", 2: "String", 3: "Complex"}"}
- Dictionary = {1: "Python" 2: "Learning", 3: "Course"}
- 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.
- String1 = '''''I'm a Geek and I live in a world of "Geeks"'''
- Print(String1) return I'm a Geek and I live in a world of "Geeks"
- stringPython = "PythonProgrammers"
- print(stringPython[0]) return 'P'
- print(stringPython[-1]) return 's'
- stringPython = "PythonProgrammers"
- print(stringPython[0:6]) return 'Python'
- 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.
- stringFormatted = "{1} {0} {2}".format('Python', 'For', 'Programmers')
- 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.

Mahesh ChandPosted Jun 24, 2019, 9:44 PM
Thank you, Hemant. Appreciate it.