Python Data Types | Mutable and Immutable Data Types

A data type, in Python or in any programming language, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. The string and int, for example, are Python data types that are used to classify text and an integer is a data type used to classify whole numbers.

Python Data Types: An Overview

One of the most crucial parts of learning any programming language is to understand how data is stored and manipulated in that language. Users use Python because of its ease of use and the number of versatile features it provides. One of those features is dynamic typing.

Classifications of Data Types in Python

Python data types are into two categories, mutable data types and immutable data types.

  • Mutable Data Types: Data types in python where the value assigned to a variable can be changed
  • Immutable Data Types: Data types in python where the value assigned to a variable cannot be changed

Mutable and Immutable Objects

Data objects of the above types are stored in a computer’s memory for processing. Some of these values can be modified during processing, but the contents of others can’t be altered once they are created in the memory.

Number values, strings, and tuple are immutable, which means you can alter their contents.

On the other hand, you can modify the collection of items in a List or Dictionary object. It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.

Immutable Data types in Python
1. Numeric
2. String
3. Tuple

Mutable Data types in Python
1. List
2. Dictionary
3. Set

Setting the Data Type in Python

In Python, the data type is set when you assign a value to a variable:

ExampleData Type
x = “Hello World”str
x = 20int
x = 20.5float
x = 1jcomplex
x = [“apple”, “banana”, “cherry”]list
x = (“apple”, “banana”, “cherry”)tuple
x = range(6)range
x = {“name” : “John”, “age” : 36}dict
x = {“apple”, “banana”, “cherry”}set
x = frozenset({“apple”, “banana”, “cherry”})frozenset
x = Truebool
x = b”Hello”bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview

Numeric Data Types in Python

When programming, if you say that a variable has a numeric value, you are being ambiguous. This is because numbers can be either integers or floats (floating points)

Python has many useful built-in data types. Python variables can store different types of data based on a variable’s data type.

It is useful for problem solvers to understand a couple of Python’s core data types in order to write well-constructed code.

Python supports four distinct numeric types: integers, long, float and complex numbers. In addition, Booleans are a subtype of plain integers. Integers or int are positive or negative whole numbers with no decimal point. Long integers have unlimited precision and float represent real numbers. Complex numbers have a real and imaginary part, a + bc, where a is the real part and b is the imaginary part.

The Python programming language provides four numeric data types. They are as follows.

  • int – All the numbers without fraction part (Example – 10). For int, there is no upper limit.
  • float – All the numbers with a fraction part (Example – 10.5). It’s accurate up to 15 decimal places
  • complex – All the numbers with real and imaginary parts (Example – 5 + 10j).
  • bool – boolean values True and False.

Integers Data Types

  • int – Signed Integers
  • long – Long integers for representing higher values

Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -101, …). An integer can also be known as an int. As with other programming languages, you should not use commas in numbers of four digits or more, so when you write 1,000 in your program, write it as 1000.

We can print out an integer in a simple way like this:

print(-25)

Output

-25

We can do math with integers in Python, too:

int_ans = 116 - 68
print(int_ans)

Output:

48

Integers can be used in many ways within Python programs, and as you continue to learn more about the language you will have a lot of opportunities to work with integers and understand more about this data type.

Floating-Point Numbers Data Types

The float data type is used to represent decimal point values.

This value is represented by float class. It is a real number with floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.

>>> c = 6.2
>>> type(c)
<class 'float'>
>>> d = -0.03
>>> type(d)
<class 'float'>
>>> e = 6.02e23
>>> e
6.02e+23
>>> type(e)
<class 'float'>

To make sure a variable is a float instead of an integer even if it is a whole number, a trailing decimal point. is used. Note the difference when a decimal point comes after a whole number:

>>> g = 5     # no decimal point
>>> type(g)
<class 'int'>
>>> g = 5.    # decimal point
>>> type(g)
<class 'float'>

Complex Numbers Data Types

Complex numbers are specified as <real part>+<imaginary part>j.

For example:

>>> 2+3j
(2+3j)
>>> type(2+3j)
<class 'complex'>

Boolean Data Types

A Boolean is such a data type that almost every programming language has, and so does Python. Boolean in Python can have two values – True or False. These values are for assigning and comparison.

Boolean data types are similar to a coin. At a time either we found head or tail, such that Boolean either return True or False. There are two constants, true and false, these constants are to assign the value to a Boolean data type.

Example 1 Boolean Data Type:

A=True;  
B=False;  
A&B ;  
A|B;

Output:

False
True

Example 2 Boolean Data Type :

print(True+False+True)

Output:

2

Note: Python treats a True value as 1 and a False value as 0. So the above example returns 2(1+0+1).

Example 3 Boolean Data Type:

print (bool(True));  
print (bool(False));  
print (bool(0));  
print (bool());  
print (bool(3))  
print (bool("Pankaj"));  
print (bool(""));  
print (bool(' '));  
print (bool(True+True));  
print (bool(False+False));  
print (bool(True+False));  
print (bool(None)); 

Output:

True
False
False
False
True
True
False 
True 
True
False 
True
False

String Data Type in Python

Strings are an immutable collection of characters. In Python, strings can store textual characters or arbitrary collection of bytes (images file contents). In python string objects are stored in a sequence.
Sequences maintain a left-to-right order among the items and are stored and fetched by their relative positions.
It’s very easy to create the strings objects in Python, any characters which are enclosed by quotes become string (quotes can ‘(single) or “(double)).

string in Python is an immutable and ordered sequence of items. They can be defined using single-quotes (') or double-quotes ("). A string spanning multiple lines can be defined using triple single-quotes (''') or triple double-quotes ("""). For example:

>>> my_var = 'This is a string'
>>> type(my_var)
<class 'str'>
>>> isinstance(my_var, str)
True

>>> my_string = """This is
... my
... first
... string"""
>>> print(my_string)
This is
my
first
string
>>> my_string_2 = '''
... This
... is
... my
... second
... string
... '''
>>> print(my_string_2)

This
is
my
second
string

Since strings in Python are ordered, we can extract individual characters from a string using their integer indices, starting with 0. The first letter of a string is always at position 0, and the positions numerically increase after that. For example:

>>> my_var = 'This is a string'
>>> my_var[0]
'T'
>>> my_var[10]
's'

Strings in Python also support slicing. Slicing is a technique which is used to extract a part of a variable using the notation [start_position:end_position], where start_position and end_position are integers indicating the length of the slice. If start_position is omitted, then slicing begins at the beginning of the string, and if end_position is omitted, then slicing ends at the end of the string. For example:

>>> my_var[0:1]
'T'
>>> my_var[0:]
'This is a string'
>>> my_var[:-1]
'This is a strin'
>>> my_var[:len(my_var)]
'This is a string' 

Tuple Data Types in Python

The tuple is similar to list in Python. In Python, the tuple data type is immutable. That means the tuples cannot be modified, unlike lists. In Python, the tuples may contain different data type values. The tuples are enclosed in parentheses. Let’s look at the code to illustrate tuples in Python.

Example – Python code to illustrate ‘Tuple’ in Python

roll_list = (1,2,3,4,5)
print(roll_list)
student = (1,'Rama',"3rd Year",86.5)
print(student)
print(type(student))
first = (1, 2, 3)
second = (4, 5, 6)

print("len(first) : ", len(first))
print("max(first) : ", max(first))
print("min(first) : ", min(first))
print("first + second :", first + second)
print("first * 3 : ", first * 3)
print("1 in first : ", 1 in first)
print("5 not in second : ", 5 not in second)

Output:

len(first) :  3
max(first) :  3
min(first) :  1
first + second : (1, 2, 3, 4, 5, 6)
first * 3 :  (1, 2, 3, 1, 2, 3, 1, 2, 3)
1 in first :  True
5 not in second :  False

This example shows several basic operations with tuples. The len() function returns the number of elements in the first tuple. Next, the max() function returns the maximum value and the min() the minimum value. The addition operator adds two tuples, the multiplication operator multiplies the tuple. The in operator determines if the value is in the tuple.

List Data Types in Python

The list is one of the most used in Python for traversing the elements. It is used along with tuples, dictionaries, and sets. The list is a collection of items/data which is ordered and can be changed whenever needed. It also allows duplicate records in the data set. Firstly, we need to understand the functionality of the list and its characteristics. Using a list we can do multiple operations such as appending, slicing, adding and removing elements, indexing, etc. and there are many different functions in the list and it goes on. Below are some of the functionalities of lists in Python.

A = [ ] # This is a blank list variable
B = [1, 23, 45, 67] # this list creates an initial list of 4 numbers.
C = [2, 4, 'john'] # lists can contain different variable types.

All lists in Python are zero-based indexed. When referencing a member or the length of a list the number of list elements is always the number shown plus one.

mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']
B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.
print(mylist[1]) # This will return the value at index 1, which is 'Grasshopper'
print(mylist[0:2]) # This will return the first 3 elements in the list.

Output:

Grasshopper
['Rhino', 'Grasshopper']

You can assign data to a specific element of the list using an index into the list. The list index starts at zero. Data can be assigned to the elements as follows:

mylist = [0, 1, 2, 3]
mylist[0] = 'Rhino'
mylist[1] = 'Grasshopper'
mylist[2] = 'Flamingo'
mylist[3] = 'Bongo'
print mylist[1]

Multidimensional lists are also allowed. Although most people can’t comprehend more than three or four dimensions. You can declare multiple dimensions by separating a with commas. In the following example, the MyTable variable is a two-dimensional array :

MyTable = [[], []]

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.

How Does A Tuple Data type Differ From The List Data Type?

Tuples do differ a bit from the list as they are immutable. Modification of a tuple is not allowed in Python. We can not add or remove any element later. Instead, Python expects us to create a new one with the updated sequence of elements.

Dictionary Data Types in Python

Dictionaries in Python are lists of Key: Value pairs. This is a very powerful data type to hold a lot of related information that can be associated through keys. The main operation of a dictionary is to extract a value based on the key name. Unlike lists, where index numbers are used, dictionaries allow the use of a key to access its members. Dictionaries can also be used to sort, iterate and compare data.

Dictionaries are created by using braces ({}) with pairs separated by a comma (,) and the key values associated with a colon(:). In Dictionaries, the Key must be unique. Here is a quick example of how dictionaries might be used:

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

We use the key to retrieve the respective value. But not the other way around.

d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error
print("d[2] = ", d[2]);

Must Read: Implementation of Stack in Python

Set Data Types in Python

Moreover, in Python, a set is a collection of an unordered and unindexed data elements of different data types. In Python, the set data type elements are immutable (restricted variables change). However, set itself is mutable. Sets starts with curly brackets. Let’s look at the code to illustrate set in Python.

Sets are separated by commas and enclosed in curly braces. Let’s take an example to understand the sets in Python.

# Set Example
myset = {"hi", 2, "bye", "Hello World"}

# loop through set
for a in myset:
    print(a)

# checking whether 2 exists in myset
print(2 in myset)

# adding new element
myset.add(99)
print(myset)

Next, we introduce some other operations to set data types

set1 = set([1, 2])
set1.add(3)
set1.add(4)

set2 = set([1, 2, 3, 4, 6, 7, 8])
set2.remove(8)

print(set1)
print(set2)

print("Is set1 subset of set2 ? :", set1.issubset(set2))
print("Is set1 superset of set2 ? :", set1.issuperset(set2))

set1.clear()
print(set1)

The add() method adds an item to the set. The remove() item removes an item from a set. The clear() method removes all items from the set. The set1 is superset of set2 if every element in set2 is also in set1. The set1 is a subset of set2 if every element in set1 is also in set2.

set([1, 2, 3, 4])
set([1, 2, 3, 4, 6, 7])
Is set1 subset of set2 ? :  True
Is set1 superset of set2 ? :  False
set([])

If we need an immutable set, we can create a frozen set with the frozenset() function.

fs = frozenset(['a', 'b', 'c'])

This line creates a frozen set from a list.

Frozenset

Frozenset is precisely the same as set only difference being it is immutable. That means you cannot modify the set once you create it. Here’s an example –

x = frozenset(("a", "b", "c", "d"))
x.add("e")

Output:

AttributeError: 'frozenset' object has no attribute 'add'

Python Data Type Conversion or Type Casting

Frequently, you will want to convert data from one type into another. In programming, we call this process typecasting. Python has tons of functions which allow us to do these type conversions on basic data types.

Integers To Floats Data Type And Vice-Versa

Integers and floats are data types that deal with numbers.

Then, to convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.

Example 1 int to float Data Type:

a_int = 3
b_int = 2

# Explicit type conversion from int to float
c_float_sum = float(a_int + b_int)
print(c_float_sum)

Output:

5.0

Example 2 int to float Data Type and Vice-Versa:

a_float = 3.3
b_float = 2.0

# Explicit type conversion from float to int
c_int_sum = int(a_float + b_float)
print(c_int_sum)

c_float_sum = a_float + b_float
print(c_float_sum)

Output:

5
5.3

Casting Different Data types to Complex Data type

Integers, floating-points can be converted to complex numbers.

Casting int Data Type to complex

>>> print(complex(1))
(1+0j)

Casting float Data Type to complex

>>> print(complex(1.0))
(1+0j)

FAQs

Do we need to define datatype explicitly in Python?

No. In Python, we do not need to declare datatypes of variables. Moreover they are interconvertible.

Does python have double data type?

No. Python has float.

Conclusion

At this point, you should have a better understanding of some of the major Python data types that are available for you to use in Python. Each of these data types will become important as you develop programming projects in the Python language.

Once you have a solid grasp of data types available to you in Python, you can learn how to convert these Python data types.

This tutorial covered the various Python data types and tried to explain each of them with examples. You may find all the relevant information here which can be useful for you in developing Python programs.

If you have any doubts do let us know in the comment section below.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments