In this article, we will learn about Python Data Types. Data types represent the type of data stored in a variable. Since Python is a dynamically typed language, there is no need to declare the data type during declaration explicitly, and the Python interpreter automatically assigns the value to its type. Below are the built-in data types available in Python
- Boolean
- Numeric
- String
- List
- Tuple
- Set
- Dictionary
Python Data Types
Python data types can be broadly classified into two categories immutable and mutable types. An immutable type is nothing, but the value remains fixed upon instantiation, and changes are not allowed after that.
For example, int is an immutable type the value cannot be changed once an instance is created, though we can reassign a new value to it, the reference will be pointing to a different address each time the value is changed.
Python Data Types – Immutable Type
- Boolean
- Numeric
- String
- Tuple
Python Data Types – Mutable Type
- List
- Set
- Dictionary
Putting all into a tabular form, just for easy remembrance
Class | Description | Immutable | Mutable |
---|---|---|---|
bool | Boolean Values | Yes | No |
int | Integer Values | Yes | No |
float | Floating-point numbers | Yes | No |
complex | Complex Numbers | Yes | No |
str | String Values | Yes | No |
list | A mutable sequence of objects | No | Yes |
tuple | An immutable sequence of objects | Yes | No |
set | Mutable collection of distinct objects | No | Yes |
frozenset | An immutable version of set class | Yes | No |
dict | Dictionary – key, value pairs | No | Yes |
Let’s take a look at each data type below.
1. Python Boolean Data Type – bool class
The Boolean data type represents the boolean values in Python. There can be only two possible boolean values True and False, and internally Python represents True as 1 and False as 0. The bool class represents the Boolean datatype in Python.
Conditions or Expressions will evaluate to either True or False. For example,
>>> a = 20 >>> b = 10 >>> if (a > b): print("a is greater than b")
In the above code, the condition evaluates to True or False based on the value of a and b.
bool class is a subclass of the int class, when you try to add bool type with int type, Python automatically upcasts them to int type.
>>> 10 + True 11 >>> 15 + False 15
We got 11 as output because the interpreter considers True as 1 and False as considered as 0 internally.
2. Python Numeric Data Type
The Numeric data type can be further divided into three subtypes
- Integer
- Float
- Complex
Integer Data Type – int class
An integer is a number without any decimal digit or fraction. The int class represents Integer values in Python. In Python, integers can hold unlimited ranged values, bounded only by the maximum memory allocated by the CPU. In most of the other programming languages, this maximum range will cause integer overflow error, but Python handles this large integer efficiently.
Integer numbers can be positive, negative, and 0 (zero).
>>> a = 20 >>> b = -30 >>> type(a) <class 'int'> >>> type(b) <class 'int'>
Here the type of both a and b is int type, are we are storing integer values(without decimal points)
The integer values also can be represented in different bases like base 2, base 8, base 16. The default base which we are using is base 10.
Binary (base 2) – can hold only two values 0 and 1, we need to use ‘0b’ or ‘0B’ as a prefix to represent the base 2
Octal (base 8) – It contains values from 0 to 7, needs to use ‘0o’ or ‘0O’ to represent base 8
Decimal (base 10) – It Contains values from 0 to 9. No prefix needed
Hexadecimal (base 16) – It contains values from 0 to 9 and alphabets A to F. We need to use the prefix ‘0x’ or ‘0X’ to represent Hexadecimal
Let take a look into the below example. We can use int(), bin(), oct(), hex() functions to convert into different bases
>>> a = 11 >>> bin(a) '0b1011' # Binary >>> oct(a) '0o13' # Octal >>> hex(a) '0xb' # Hexadecimal
Float Point Data Type – float class
The floating points numbers can be identified by the decimal point or the fractional part in them. The float class represents the floating-point numbers in Python. Floating-point numbers can also be positive, negative, and 0 (zero).
For example, below are some of the valid floating-point numbers
10.2, -3.456, 0.0123
The Floating-point numbers consist of three parts sign, exponent, and a fraction ( or mantissa), and Python supports only Double-precision, which takes up to 64 bits of memory.
We can also represent Floating point numbers in scientific notation where we use ‘e’ or ‘E’ to represent the power of 10.
For example, We can represent 3.14 x 103 as 3.14e3
Complex Numbers – complex class
The Complex numbers consist of real and imaginary parts, and both joined with a ‘+’ or ‘-‘ sign. The imaginary part should always be followed by a ‘j’. The complex class represents the Complex numbers in Python.
Below are some of the examples of a Complex number in Python
110 + 15j , -12.5 + 3.4j
Whenever the real part is 0, then we can omit it.
For example, Instead of writing 0 + 5j, we can write 5j alone this will also be considered as a complex number
>>> 0 + 5j 5j
With real and imag attributes of the complex number, we can get the real and imaginary part separately by calling variable.real and variable.imag
>>> val = 10 + 14j >>> val.real 10.0 >>> val.imag 14.0
3. Python String Data Type – str class
The String is an immutable data type in Python that holds up a sequence of Unicode characters, which is represented by the str class in Python.
We can enclose a string with either a single quote or a double quote, and both are valid. In the below example, both msg1 and msg2 are a valid declaration of a string.
>>> msg1 = 'Welcome to JavaInterviewPoint' >>> msg2 = "Welcome to JavaInterviewPoint"
We can also create a string using triple single quotes (”’) or triple double quotes (“””)
>>> msg3 = ''' Triple Singe Quote Valid String ''' >>> msg4 = """ Triple Double Quote Valid String """
The Triple Single Quote and Triple Double Quotes can be used as a multiline comment and comes in handy when you want to embed another string or allows you to create a string that spans across multiple lines.
For example
>>> msg5 = """ Welcome To 'JavaInterviewPoint' """ >>> print(msg5) Welcome To 'JavaInterviewPoint'
Using the Triple double quote, we have created a multiline string and added a single quote to ‘JavaInterviewPoint’
Python, by default, uses UTF-8 Unicode encoding, we can use any Unicode characters in our string without any issues. For example, let’s add Unicode for dollar sign in our string and print it.
>>> dollar = "\u0024 \U00000024" >>> dollar '$ $'
We can use the str() function to convert other data types to str type. The str() function takes up three parameters, the first parameter is any convertible type of value, and the other two parameters are optional, one for specifying the encoding and the other for error handling.
>>> str(12) '12' >>> str(5.6) '5.6' >>> str(True) 'True' >>> str(-1.2) '-1.2'
4. Python List – list class
The List is a mutable sequence of objects, and the list class represents the List type in Python. Lists are array-based sequences, and the index starts from zero to n-1. We need to use square brackets [] to represent a list and comma ‘,’ to separate the elements of the list.
>>> val = [1, 5.4, 'Welcome'] >>> val [1, 5.4, 'Welcome'] >>> type(val) <class 'list'>
In the above snippet, we have created a list ‘val’, with three different value types integer, float, and string.
Though list and arrays sound similar, the list can store different types of elements, but arrays can store only one type of element, and one more fundamental difference is that list can grow dynamically whereas the arrays are fixed-sized and cannot grow dynamically.
Using the list() function, we can convert any iterable such as Set, Tuple, etc. type into a list.
For example,
>>> colorSet = {'Red', 'Blue', 'Green', 'Yellow'} >>> fruitsTuple = ('Apple', 'Orange', 'Banana') >>> colorsList = list(colorSet) >>> colorsList ['Red', 'Yellow', 'Green', 'Blue'] >>> fruitsList = list(fruitsTuple) >>> fruitsList ['Apple', 'Orange', 'Banana']
In the above code, we have created a set (colorSet) and tuple (fruitsTuple), and we have converted both of them into a list (colorsList and fruitsList)
A list can hold another list in it, let’s try that scenario as well.
>>> newFruitsList = ['Kiwi', 'Grapes', fruitsList] >>> newFruitsList[0] 'Kiwi' >>> newFruitsList[1] 'Grapes' >>> newFruitsList[2][1] 'Orange' >>> newFruitsList[2][2] 'Banana'
We have added the fruitsList into our newFruitsList, and we can access the elements by using double square brackets [ ][ ]
5. Python Tuple – tuple class
The Tuple is an Immutable sequence of objects, and the tuple class represents a Tuple in Python. A tuple is almost similar to a list except for the fact the list is mutable, and tuple is immutable.
For Tuple also the index starts from zero to n-1, and we need to use brackets () to represent a tuple and comma ‘,’ to separate the elements of the tuple.
let’s create a tuple
>>> numberTuple = (1, 2, 3, 4, 5) >>> fruitsTuple = ('apple', 'orange', 'banana') >>> mixedTuple = (1, 10.5, -13.2, 'Welcome')
We can access the element of the tuple using the index.
>>> numberTuple[1] 2
But Once we have created a tuple, we cannot add a new element or change an element at a particular index in a tuple. When we try to change or add a new element, we will get ‘tuple’ object does not support item assignment error.
>>> numberTuple[5] = 6 Traceback (most recent call last): File "<pyshell#18>", line 1, in numberTuple[5] = 6 TypeError: 'tuple' object does not support item assignment >>> numberTuple[1] = 11 Traceback (most recent call last): File "<pyshell#19>", line 1, in numberTuple[1] = 11 TypeError: 'tuple' object does not support item assignment
6. Python Set – set class
A Set is an unordered mutable sequence of unique objects. The set class represents Sets in Python. Sets are mutable, and we can add or remove items in a Set. Since they are unordered, they will not have index positions, and we cannot perform indexing or slicing operations.
We need to use curly braces {} to represent a set and comma ‘,’ to separate the elements of the set. Let’s create a simple set
>>> val = {1, 10.5, "Welcome"} >>> type(val) <class 'set'>
Since set are unordered and contain unique elements, let’s try creating a set with a duplicate item and see what happens
>>> numberSet = {1, 2, 3, 1, 5, 6, 2} >>> numberSet {1, 2, 3, 5, 6}
We have a created a set (numberSet) with duplicate entries. We have added 1 and 2 twice while creation. Though it didn’t complain about duplicate items during creation, the duplicate elements got truncated.
Since sets are mutable, we are allowed to add elements to a set after creation. We can use add() function to add an element to a set. Let’s add a new element to the above set.
>>> numberSet.add(7) >>> numberSet {1, 2, 3, 5, 6, 7}
The main advantage of using a set over a list is that it has a highly optimized method for checking whether a specific element is present in the set or not, as it internally uses hashtable for storing and retrieving the data.
7. Python FrozenSet
A frozenset is an immutable version of a Set. They have all the properties similar to a Set, but you cannot perform any modification operation on a FrozenSet.
We can create a frozenset by calling the frozenset() function, which takes an iterable as a parameter.
>>> numberFrozenSet = frozenset([1, 2, 3]) >>> numberFrozenSet frozenset({1, 2, 3})
The frozenset also doesn’t allow duplicate values like a Set
>>> numberFrozenSet = frozenset([1, 2, 3, 1, 4, 2]) >>> numberFrozenSet frozenset({1, 2, 3, 4})
Even if we try to add also the frozenset truncates it.
Unlike a set, frozenset is immutable; we cannot make any modifications to the frozenset after creation. It doesn’t have the ‘add’ attribute, and even if we try to add an element, it will throw an error
>>> numberFrozenSet.add(11)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
numberFrozenSet.add(11)
AttributeError: 'frozenset' object has no attribute 'add'
8. Python Dictionary – dict type
The Dictionary or Mapping is a mutable unordered set of key-value pairs. Whenever we are adding a key to the dictionary, we must also add a value to it (which is changeable at later point). The dict class represents the dictionary in Python.
We need to use curly braces {} to represent a dictionary. The key and its value should be separated by a colon ‘:’ and each key-value pair should be separated by a comma ‘,’. Let’s create a simple dictionary
>>> numbers = { 1 : 'One', 2 : 'Two', 3 : 'Three'} >>> type(numbers) <class 'dict'>
We can access the elements of a dictionary using the key like below.
>>> numbers[2] 'Two' >>> numbers[1] 'One'
Since dictionaries are mutable, we can modify the value associated with a key. Let’s try changing the value to ‘TTTWWWOOO’ for key ‘2’
>>> numbers[2] = 'TTTWWWOOO' >>> numbers[2] 'TTTWWWOOO'
Note: We cannot change the key associated with a value. It can only be the other way.
Keys can have only immutable hashable objects such as int, float, str, bool, frozenset, tuple, but mutable types such as list, set, dict is not permitted. On the other hand, the values can be of any datatype. Let’s try to add a mutable type as a key and see what happens?
>>> l = [1, 2, 3] >>> s = {1, 2, 3} >>> type(l) <class 'list'> >>> type(s) <class 'set'> >>> test = {l : 'List'} Traceback (most recent call last): File "<pyshell#15>", line 1, in test = {l : 'List'} TypeError: unhashable type: 'list' >>> test = {s : 'Set'} Traceback (most recent call last): File "<pyshell#16>", line 1, in test = {s : 'Set'} TypeError: unhashable type: 'set'
We have created a list and set, and added as a key to the test dictionary. Since they are mutable types, Python throws ‘TypeError: unhashable type’ error.
Let’s now try to add a tuple as a key to the dictionary since tuple is an immutable hashable type, and Python should not complain.
>>> t = (1, 2, 3) >>> type(t) <class 'tuple'> >>> test = {t : 'Tuple'} >>> test {(1, 2, 3): 'Tuple'} >>> test[(1, 2, 3)] 'Tuple'
Happy Learning!!
Leave a Reply