# Data Types in Python

We can classify all the information in the world into different categories for better understanding. Data in a programming language such as Python is no exception. Data types in Python help us classify or categorise data items and tell us what operations we can perform on a particular data.

source: medium.com

As Python is an object-oriented programming language and all values are objects, we can say that data types in Python are classes, and variables are the instance (object) of these classes. Let us look at some of the standard and built-in data types in Python.

## Python Numbers

The numbers data type represents data that has a numeric value. These can be integers, floating-point numbers or complex numbers, and we defined them under the int, float, and complex classes in Python.

Integers – In Python, there is no limit to how long an integer value can be. The length is restricted by the amount of memory your system has, but essentially an integer can be as long as you want it to be. Integers fall under the int class and contain positive or negative whole numbers (without fraction or decimal).

Float – We represent a float value by the float class and is a real number with a decimal point (floating-point representation). The only difference between an integer and a floating-point number is the decimal point. For example, if 34 is an integer, then 3.4 is a floating-point number.

Complex Numbers – We show a complex number as (real part) + (imaginary part)j. For example, 5 + 9j

                    
>>> x = 67890123456789012345
>>> x
1234567890123456789
>>> y = 67.890123456789012345
>>> y
67.89012345678901
>>> z = 9+5j
>>> z
(9+5j)




If you observe the above example, you will see that y (float value) was truncated. This is because a floating-point number is accurate only till the 15th decimal place.

If you want to find out which class a variable belongs to, you can use the type() function. In the same way, we can use the isinstance() function to check if a value belongs to a particular class.

                    
s = 5
print(s, "is of type", type(s))

s = 2.0
print(s, "is of type", type(s))

s = 1+2j
print("is", s, "a complex number?", isinstance(9+5j,complex))




Output:

                    
5 is of type <class 'int'>
2.0 is of type <class 'float'>
Is (1+2j) a complex number? True




## Python List

In Python data types, sequences are the ordered collection of similar or different data types. Using sequences we can store multiple values in an organised and efficient way. List, string, and tuples are the types of sequence data types.

Lists are similar to arrays that are declared in other languages and are ordered collections of data. Lists are flexible and allow us to store items of different types in a set order. We use the square brackets [] to declare a list and separate each item with a comma.

                    
p = [38, 0.243, 'my Python']



Since lists are ordered, each item in a list has an index value, and we can use the index to extract specific items from a list. You should remember that the Python index always starts from 0.

                    
p = [2,4,6,8,10,12,14,16]

# getting the 3rd item from a list
print(p[2])

# getting the first 5 items
print(p[0:5])

# getting the last three numbers
print(p[5:])




Output:

                    
6

[2, 4, 6, 8, 10]

[12, 14, 16]



We can also change the values of a list item in the following manner:

                    
p = [2,4,6,8,10,12,14,16]

p[5] = 9

print (p)



Output:

                    
[2, 4, 6, 8, 10, 9, 14, 16]



## Python Tuple

A tuple is similar to a list in many aspects and is also an ordered sequence of data types in Python. However, unlike a list, the items in a tuple are immutable. That means we cannot change the item values once we assign them to a tuple, but we can reassign or delete an entire tuple.

The immutable nature of tuples helps programmers manipulate them faster when compared to a list. As the elements remain constant throughout the program, using tuple prevents any accidental changes in the data sequence. We define the items in a tuple within parenthesis or round bracket (“(…)”) and separate each item with a comma.

                    
p = (38, 0.243, 'my Python')



We can retrieve the items using the slice operator []. However, we cannot change their values.

                    
p = (38, 0.243, 'my Python')

# getting the first two items

print (p[0:2])

# try to change an item value

# it throws an error

p[1] = 6

print(p)



Output:

                    
(38, 0.243)

Traceback (most recent call last):

File "", line 2, in

TypeError: 'tuple' object does not support item assignment



## Python Strings

A string is represented by the str class and is a collection of Unicode characters. We usually use single or double quotes to represent a line of string. On the other hand, we use triple quotes ”’ or “”” to represent multi-line strings.

                    
p = "Let us have fun with strings"
print(p)

p = '''We can give more
information through a
multiline string'''
print(p)



Output:

                    
Let us have fun with strings

We can give more
information through a
multiline string



Just like in lists and tuples, we can use the slice operator in strings to retrieve a specific character. However, we cannot change it as strings are immutable.

                    
p = 'Let us have fun'

# getting the first 4 characters
print(p[0:5])

# try to change a character
# it throws an error
p[5] = o




Output:

                    
Let u

Traceback (most recent call last):
File "", line 8, in
TypeError: 'str' object does not support item assignment




## Python Set

A Set is an unorganised and unindexed collection of items. That means the items do not have a defined order and may appear in a different order every time we use them. Hence, they cannot be accessed using a key or index. A Set does not allow duplication of items. We cannot change these items that are enclosed within curly brackets (“{…}”) either.

                    
>>> p = {3,7,34,9,23}
>>> print (p)

{34, 3, 7, 9, 23}




We can perform certain operations line union and intersection on two different sets.

                    
p = {3,7,34,9,23}
q = {7,34,20,8,5}

# the union operator
# joins two sets without duplicates
r = set.union(p,q)
print (r)

# the intersection operator
# gives common items
r = set.intersection(p,q)
print (r)




Output:

                    
{34, 3, 5, 7, 8, 9, 20, 23}
{34, 7}




## Python Dictionary

Dictionaries store an ordered collection of items where each item is mutable that we identify using a key name (or key). Unlike an index, a key can be of any data type, such as string, float, integer, etc. and is more flexible.

A dictionary has the following syntax:

variable = {key1 : item1, key2 : item2...}

We define a dictionary item within {} as a key: value pair, and we use commas to separate each item pair.

                    
p_dict = {'name': 'Lucy', 'country': 'Austria', 'number' : 234}
type(p_dict)

# getting a value using its key
print(p_dict['name'])

p_dict['age'] = 34
print (p_dict)

# trying to use value to get a key
# throws an error
print (p_dict['Lucy'])




Output:

                    
Lucy

{'name': 'Lucy', 'country': 'Austria', 'number': 234, 'age': 34}

Traceback (most recent call last):
File "", line 14, in
KeyError: 'Lucy'




## Conversion Between Data Types

Converting one data type in Python to another is a straightforward process as we use conversion functions like int(), float(), str(), etc.

                    
# converting float to int
#  number gets truncated to a whole number

>>> int(8.394)
8

# converting number to string
>>> str(374)
'374'

# converting string to int is not possible
# int() only accepts numeric values
>>> int('155q')
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '155q'




Similarly, we can even convert one sequence data type to another.

                    
# to set
>>> set(['hi',64.9,45])
{64.9, 'hi', 45}

# to tuple
>>> tuple({'hi','name',45})
('name', 'hi', 45)

# to list
>>> list ('Acapella')
['A', 'c', 'a', 'p', 'e', 'l', 'l', 'a']

# to dictionary
# each item should be a pair
>>>dict([['name', 'Paul'], ['age', 14]])
{'name': 'Paul', 'age': 14}




## Questions and Answers on Data Types in Python

Q1. What are the 4 data types in Python?

Answer: In a programming language like Python, there are mainly 4 data types:

• String – It is a collection of Unicode characters (letters, numbers and symbols) that we see on a keyboard.
• Numerical – These data types store numerical values like integers, floating-point numbers and complex numbers.
• Boolean – A boolean is used when we wish to restrict data to True/False or yes/no options.
• Sequence types – These help us store ordered collection of similar or different data types. List, string, and tuples are the types of sequence data types.

Q2. What are the 5 data types in Python?

Answer: Apart from the four main data types mentioned above, sets and dictionaries are data types that are unordered and non-indexed. We cannot change any item value after we define it in a dictionary or set. We also cannot access an item using an index value.

Q3. What is a data type in Python?

Answer: We can say Python data types are collections of data items that help us classify or categorise data. Every value in Python has a data type, and every data type is a class that stores a variable (object). Python offers us many data types like int, float, string, set, list, etc.

Q4. How many data types are there in Python?

Answer: If we look at all the various data types in Python, there are nine data types. The integer, float, and complex data types fall under the numerical data type. They store numerical values as whole numbers, floating-point numbers, and complex numbers, respectively.

List, tuple, and strings come under the sequence data type that can store data in order. They are flexible and we can change each item in their sequence.

Dictionary and set data types are unique. While a set is unorganised and unindexed, a dictionary is ordered. However, it is non-indexed and we define an item as a key:value pair. Apart from these, there is the boolean data type that stores data in the form of true or false.

Share with friends

## Customize your course in 30 seconds

##### Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
Ashhar Firdausi
IIT Roorkee
Biology
Dr. Nazma Shaik
VTU
Chemistry
Gaurav Tiwari
APJAKTU
Physics
Get Started