In previous chapters, we dealt with variables many times. We used them to store values like 10 (which is an integer), “Hello World” (which is text) and many more. In fact, we can use variables to store many more types of data like a list of integers, decimal values, etc.
The different types of data like an integer and a text are not the same for us and neither for Python or a computer. In fact, different types of data also need a different amount of space to get stored in memory. For example, the amount of memory needed to store a text value and an integer value is different. Thus, Python has different built-in data types to handle different data. We will look at those different types of data in this chapter.
type() Function in Python
Python also provides a function type()
to get the type of any data. Let’s look at an example.
print(type(10))
We passed the value 10 to the type()
function and printed the result. We got the output as <class 'int'>. This means that the data type of 10 is int (integer).
Let’s check the data type of 10.5.
print(type(10.5))
Here we got the output as <class 'float'>, which means that data type of 10.5 is float (a number with decimal).
Let’s look at some important data types in Python.
- Numbers
- Boolean
- String
- List
- Tuple
- Dictionary
- Set
We will go through only a brief introduction of the String, List, Tuple, Dictionary and Set data types because these are explained in detail in separate chapters.
Python Numbers
Numbers consist of all the numeric values. Numbers in Python are classified into the following data types.
- int - Integers don’t have decimal and can have any length as long as the required memory is available. For example, 3, 855, etc.
- float - Floating point numbers are the ones having decimal. For example, 2.564728.
- complex - Complex numbers, as in Mathematics, have the form
a + bj
, wherea
is the real part andb
is the imaginary part. For example, 2 + 3j, 6j.
a = 56
print(a, "has a type", type(a))
b = 56.48
print(b, "has a type", type(b))
c = 5 + 6j
print(c, "has a type", type(c))
In the above example, variables a
, b
and c
are given values of type int, float and complex respectively.
Python Boolean
A Boolean data type consists of two values - True
and False
. These two values are also the keywords reserved by Python.
print(True, "has a type", type(True))
print(False, "has a type", type(False))
We can see that the type of True
and False
is bool
(bool is for Boolean). We can also assign any variable a value of True
or False
. See the example given below.
a = True
b = False
print(a)
print(b)
Python String
String is a collection of characters. In simple English, it is a letter, word, sentence or a collection of sentences. You will go through a whole chapter on string later. So, leave it for that time. For now, just understand that a string is a collection of characters and these are written within ' '
or " "
. So, Hello World written within ' '
i.e. 'Hello World'
is a string.
print("Hello World", "has a type", type("Hello World"))
print('Hello World', "has a type", type('Hello World'))
print('word', "has a type", type('word'))
print('a', "has a type", type('a'))
print('@', "has a type", type('@'))
print('23', "has a type", type('23'))
Note that anything written within ' '
or " "
is a string. In the above example, ‘@’ and ‘23’ are also of type str
(str is for String).
Look at another example.
a = "23"
print(a, "has type", type(a))
b = 23
print(b, "has type", type(b))
You can see that the data type of the value assigned to a
is str because it is written within ""
.
' '
or " "
is treated as a string and not as an integer or a float. For example, print(type("8"))
will give us <class 'str'>
.
Python List
A list is a collection of items.
The items in a list are enclosed within brackets [ ]
and separated by commas.
a = [2, "Hello", True, 100, 2]
Here [2, "Hello", True, 100, 2]
is a list.
a = [2, "Hello", True, 100, 2]
print(a, "has type", type(a))
Python Tuple
Tuples are the same as lists. The difference is that tuples are immutable while lists are not. This means that once tuples are created, they cannot be modified.
The items in a tuple are enclosed within parentheses ( )
and separated by commas.
a = (2, "Hello", True, 100, 2)
Here (2, "Hello", True, 100, 2)
is a tuple.
a = (2, "Hello", True, 100, 2)
print(a, "has a type", type(a))
Python Dictionary
A dictionary is a collection of data in the form of key-value pairs. It can be understood as a mapping structure where keys are mapped to values.
Let’s just look at an example, you will go through an entire chapter on dictionary later on.
fruit = {'mango':40,'banana':10,'cherry':20}
Here, the dictionary has three items - 'mango':40
, 'banana':10
and, 'cherry':20
In the first item, the key is mango
and the value is 40. Similarly, there is a key-value pair in the other two items as well.
fruit = {'mango':40,'banana':10,'cherry':20}
print(fruit, "has type", type(fruit))
Python Set
A set is an unordered collection of unique and immutable items. This means that the items in a set cannot be repeated and cannot be changed after the set is created. We can also perform mathematical operations like union, intersection, etc., with sets.
The items in a set are enclosed within braces { }
and separated by commas.
a = {1, 2, 3}
Here {1, 2, 3}
is a set.
a = {1, 2, 3}
print(a, "has type", type(a))
Type Conversion
Suppose we are writing some code and we have a variable having a value 10 (an integer) and at some point of time we want it to be a string i.e., “10”. Or a more practical case would be to convert a float (10.2) to an integer (10). We can easily do so in Python. Let’s see how.
Python provides a list of functions for converting from one data type to another.
Python int()
It converts a value into an int.
Floating point numbers can be converted to integer.
print(int(4.6))
If a Boolean value is converted into an int, then True
returns 1
and False returns 0
.
print(int(True))
print(int(False))
If a string consists of only numbers, then it can be converted into an integer.
print(int("10"))
However, if a string consists of some non-numeric value, then it will throw an error on converting it to integer.
print(int("Hello"))
Python float()
It converts a value into a float.
Integers can be converted to float.
print(float(46))
If a Boolean value is converted into a float, then True
returns 1.0
and False
returns 0.0
.
print(float(True))
print(float(False))
If a string consists of only numbers, then it can be converted into a float.
print(float("10"))
print(float("4.6"))
However, if a string consists of some non-numeric value, then it will throw an error on converting it to float.
print(float("Hello"))
Python str()
It converts a value into a string.
It can convert numbers, boolean values and also list, tuples, dictionaries and tuples into strings.
a = str(46)
print(type(a))
From the above example, we can see that the integer (46) got converted into a string (‘46’).
print(str(46))
print(str(4.6))
print(str(True))
print(str([1, 2, 3, 4]))
print(str({'a':'1','b':'2'}))
Python bool()
It converts a value into a boolean.
If a non-zero value is passed to the bool()
function, then it returns True
. Otherwise, if a null value (0, 0.0, etc), a False value (value or expression equivalent to False), None or an empty sequence or mapping ([ ], { }, ( ), etc) is passed to the function, then it returns False
.
print(bool(0.5))
print(bool(True))
print(bool(False))
print(bool(0.0))
print(bool(None))
print(bool("Hello"))
print(bool([ ]))
Apart from these functions, there are functions list(), tuple(), dict() and set() to convert values to list, tuple, dictionary and set respectively which we will cover in their respective chapters.
Python type() and Python isinstance()
As you have seen, the type()
function is used to determine the data type of a variable or a value.
print(type(10))
In the above example, we can see that the data type of 10 is int.
However, you must be wondering why we are getting the type as class 'int'
. What is the significance of ‘class’?
In Python, data types are predefined classes and variables/values are the objects of these classes. Therefore, in the above example, int is a class and 10 is an object of int. Don’t worry if you are not getting this. You will learn about classes and objects later. For now, just keep in mind that int is a class and 10 belongs to the class int. Similarly, str is a class and “Hello World” belongs to the class str, list is a class and [1, 2, 3] belongs to the class list, and so on.
isinstance()
function is used to check if an object belongs to a particular class.
Look at the following example.
print(isinstance(3, int)
isinstance(3, int)
returned True
because 3 is of type int or we can say that 3 belongs to the class int.
Let’s see some more examples.
a = 3
print(isinstance(a, float))
b = "Python"
print(isinstance(b, str))
c = True
print(isinstance(c, bool))