0% found this document useful (0 votes)
4 views11 pages

02 Python Data Type

The document provides an overview of Python data types, categorizing them into mutable and immutable types. Mutable types, such as lists and dictionaries, allow for changes after creation, while immutable types, like strings and tuples, do not permit modifications. It also discusses the characteristics, examples, and differences between these data types, highlighting their applications in programming.

Uploaded by

rshxyxyxy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

02 Python Data Type

The document provides an overview of Python data types, categorizing them into mutable and immutable types. Mutable types, such as lists and dictionaries, allow for changes after creation, while immutable types, like strings and tuples, do not permit modifications. It also discusses the characteristics, examples, and differences between these data types, highlighting their applications in programming.

Uploaded by

rshxyxyxy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Data Types

Python is one of the most popular programming languages that offers a rich set of data
types. A Python data type defines the type of data stored in a variable. Unlike Java, C, and C++ in
Python, we do not specify the variable’s data type explicitly. The data type in Python is
automatically detected when the value is stored in the variable.
Python data type is categorized into two types:
 Mutable Data Type – A mutable data type is those whose values can be changed.
 Example: List, Dictionaries, and Set
 Immutable Data Type – An immutable data type is one in which the values can’t be
changed or altered.
 Example: String and Tuples
In this article, we will discuss Mutable and Immutable data types and the Difference Between
Mutable and Immutable in Python based on different parameters.
Difference Between Mutable and Immutable Data Type: Mutable vs Immutable
Mutable Immutable

Data type whose values can be Data types whose values can’t be
Definition
changed after creation. changed or altered.

Retains the same memory


Memory Any modification results in a new
location even after the content is
Location object and new memory location
modified.

Example List, Dictionaries, Set Strings, Types, Integer

It is memory-efficient, as no new
It might be faster in some scenarios as
Performance objects are created for frequent
there’s no need to track changes.
changes.

Not inherently thread-safe.


They are inherently thread-safe due to
Thread-Safety Concurrent modification can lead
their unchangeable nature.
to unpredictable results.

When you need to modify, add,


When you want to ensure data remains
Use-cases or remove existing data
consistent and unaltered.
frequently.

Mutable Data Type in Python


In Python, a data type is mutable if its values can be changed, updated, or modified after the data
type has been created. In other words, once an object of the mutable data type is initialized, you can
update its content without creating a new object.
Examples of Mutable Data Type:
Python Lists
Python lists methods are mutable; the list’s contents be modified in place. You can change a list in
place, add new elements, overwrite existing elements, or delete them. Also, note that the same
value can occur in a list more than once.
Example: List1 = [‘Python’, 3.0, ‘Shiksha Online’, ‘Python Courses’]
#create a list of student

name = ['Vikram', 'Anshul', 'Amit', 'Suresh']

#add element in the existing list


[Link]('Kamal')

#print the result


print(name)

Python Dictionary
Dictionaries are likely the most important and flexible mutable built-in data types in Python. In
simple terms, a Python dictionary is a flexible-sized arbitrary collection of key-value pairs, where
key and value both are Python objects.
Example: Dict_1 = {‘first_name’: ‘Amit’, ‘age’: 44, ‘job’:’Professor’}

# Create a dictionary: Employee

employee = {'name' : 'Vikram', 'age' : 30, 'department' : 'Content Management'}

# change the department name from Content Management to Editorial

employee['department'] = 'Editorial'

#print the dictionary

print(employee)

Python Sets
Sets are unordered collections of unique elements and immutable objects. You can think of them as
a dictionary with just the keys and their values thrown away. Each item of a set should be unique.
While sets themselves can be mutable, that is you can add or remove items, however, the items of a
Python set must be of an immutable type.
Example: set1 = {1, 2, 3, 4, 5, 6, 7}

# Creating a set
name = {'Vikram', 'Anshul', 'Amit', 'Suresh'}

# Displaying the original set


print("Original set:", name)

# Adding an element to the set


[Link]("Kunal")
print("After adding 'Kunal':", name)

# Removing an element from the set


[Link]("Amit")
print("After removing 'Amit':", name)

# Adding multiple elements using the update method


[Link](["Ankit", "Harsh"])
print("After adding 'Ankit' and 'Harsh':", name)

Immutable Data Type in Python


Data types in Python whose values can’t be changed or modified are known as Immutable Data
Types. Once the value or the object of the immutable data type is initialized, its value remains
constant throughout its lifetime.
But, if you want to change the original object, a new object will be created with the modified
values.
Common Immutable Data Types in Python are:
Integers (int)
 It represents whole numbers, both positive and negative.

 Once an integer object is created, its value remains fixed. You cannot change the value of an
existing integer object.
Floating Points (float)
 It represents real numbers with decimal points.

 Likeintegers, once a floating-point number is initialized, its value remains constant and
cannot be altered.
Strings (str)
 Strings are ordered sequences of characters used to represent text.

 Once a string is initialized, its content is fixed. You cannot modify individual characters
within the string.
Tuples (tuple)
 They are ordered collections of elements, similar to lists.

 The main distinction between tuples and lists is that tuples are immutable.
 This means that once a tuple is created, its content cannot be changed.
Booleans (bool)
 Booleans represent truth values and can only take True or False values.

 These values are constants in Python and cannot be changed.


Frozensets (frozenset)
 They are like sets, but they are immutable.

 Thismeans you can’t add or remove elements from a frozen set after it’s been created. They
are useful when you need a set-like structure that shouldn’t be modified.

"""
This program shows how strings and tuples are immutable in Python.
"""
my_string = "Hello, world!"

try:
"""
This code tries to change the first character of the string to "H".
However, the code will throw a TypeError because strings are immutable.
"""
my_string[0] = "H"
except TypeError:
print("Strings are immutable and cannot be changed.")

my_tuple = (1, 2, 3)

try:
"""
This code tries to change the first element of the tuple to 4.
However, the code will throw a TypeError because tuples are immutable.
"""
my_tuple[0] = 4
except TypeError:
print("Tuples are immutable and cannot be changed.")

print("The value of the string is:", my_string)

print("The value of the tuple is:", my_tuple)

Key Similarities and Difference Between Mutable and Immutable Data Types in Python
 Both Mutable and Immutable data types can be used to store data and can be accessed using
the same syntax.
 Mutabledata types can be changed after creation, whereas immutable data types can’t be
changed after creation.
 i.e., you can add, remove, or modify the contents of a mutable data type but
can’t do the same with an immutable data type.
 Mutable data types are more memory intensive than immutable data types as mutable data
types store a copy of their content whenever they are changed.
 Immutable data types are less prone to errors than the mutable data type.

Python Data Types


Developed by Guido van Rossum in 1991, Python is one of the most widely used
programming languages in the technical field. Due to its simple and easy-to-use syntax and
standard data types, Python finds its application in Machine Learning, Web Development, Artificial
Intelligence, and many more fields. This blog will help you understand what are Python data types.
We will also discuss the functionality of each data type in Python with examples in detail.

What is a Data Type in Python?


Python data types are referred to as the classification of different data items. It represents
different types of variables that inform what operations a user can perform on specific data items.
Since everything in the Python programming language is identified as an object, data types are
classified as classes and variables as objects of the same classes.

A variable holding a value will always have a data type. With Python being a dynamic type
of programming language, there is no need for the users to specify the variable type while declaring
it. It is the interpreter who implicitly binds the value of the variable with the data type. Moreover,
Python provides the type () function to determine a particular variable’s data type.

For example –
a=6

The variable in the given example holds an integer value of six, and the data type is not
defined. Python interpreter will implicitly interpret the variable ‘a’ as an integer type.

Different Data Types in Python

The following are the different data types in Python with examples.

1. Standard or Built-in Python Data Types

As discussed above, a variable can hold multiple values. For instance, Python stores an
individual name as a string and its ID as an integer. It provides access to several standard or built-in
data types defining the storage method on each of them.
The following are the standard or built-in data types in Python.

 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

2. Mutable Data Type in Python

The mutable data types are those data types whose values can be changed after creating them.
The following are the mutable data types in Python:

 Lists
 Dictionary
 Sets
3. Immutable Data Type
The immutable data types are those data sets whose values can’t be changed after creating them.
The following are the immutable data types in Python:

 Numeric
 Strings
 Tuples

4. Numeric Data Type


The numeric data types represent or store the data having numeric values. Python numeric
data type can be in the form of an integer, floating values, or complex numbers. Python
uses int, float, and complex classes to define these values.

It supports the following listed numeric data types:

* Integers (int)

The numeric data type represented by the int class, integers, includes positive and negative
whole numbers, excluding fractions and decimals. In Python, there is no limitation on the length of
the integer value. For example, 5, 13, 87, -65, -47, -98, etc.

* Floating Numbers (float)

The numeric data type is represented by the float class, the floating numbers contain real,
floating-point numbers. For example, 1.6, 6.65, 43.8, etc. This specific class can store floating-point
numeric values up to 15 decimal points.

* Complex Numbers (complex)

The numeric data type represented by the complex class, the complex numbers, contain an
ordered pair- x + by [(real part + imaginary part)j]. For example, 3 + 6j, 7 + 5j, etc.

For Example,

value1 = 10
print(value1, 'belongs to the', type(value1).__name__, 'class')

value2 = 5.0
print(value2, 'belongs to the', type(value2).__name__, 'class')

value3 = 2 + 4j
print(value3, 'belongs to the', type(value3).__name__, 'class')

Output -

10 belongs to the int class


5.0 belongs to the float class
(2+4j) belongs to the complex class

5. Sequence Data Type

The sequence data type represents the ordered collection of similar or different data types.
With the help of sequence data type, users can store several values in an organized and efficient
way.

Python supports the following listed sequence data types:

* String
In Python, strings are a sequence of bytes that represents Unicode characters. A string is
typically a collection of one or more characters that a user can put in a single, double, or triple
quote. The ‘str’ class represents the string data type in Python.

Now that Python provides built-in functions and operators for performing operations in the string, it
becomes easier for you to handle this particular data type in Python.

For example,

// String with single quotes

str1 = 'Welcome to the Mathematics Lecture'


print("String created using Single Quotes:")
print(str1)

// String with double Quotes

str2 = "I'm a Mathematician"


print("\nString created using Double Quotes:")
print(str2)
print(type(str2))

# String triple Quotes

str3 = '''I'm a Mathematics professor in University of California'''


print("\nString created using Triple Quotes:")
print(str3)
print(type(str3))

Output -

String created using Single Quotes:


Welcome to the Mathematics Lecture

String created using Double Quotes:


I'm a Mathematician
<class 'str'>

String created using Triple Quotes:


I'm a Mathematics professor in University of California
<class 'str'>

* List
The list data type is similar to the arrays – an ordered collection of data. This data type is
relatively flexible since there is no need for the items in the list to be of the same type. You can
create lists in Python simply by putting the items inside the square brackets []. Subsequently, to
separate the items stored in the lists, you can use a comma (,).
For example,

// Empty list
my_list = []
print("Initial empty list:")
print(my_list)

// List with a string


my_list = ['TimeAndSpace']
print("\nList with a string:")
print(my_list)

// List with multiple values

my_list = ["Time", "And", "Space"]


print("\nList with multiple values:")
print(my_list[0])
print(my_list[2])

// Multi-dimensional list

nested_list = [['Time', 'And'], ['Space']]


print("\nMulti-Dimensional List:")
print(nested_list)

Output -

Initial empty list:


[]

List with a string:


['TimeAndSpace']

List with multiple values:


Time
Space

Multi-Dimensional List:
[['Time', 'And'], ['Space']]

* Tuple

Similar to the list data type, the tuple data type in Python is also an ordered collection of
items of different types. One single difference between these two data types is that tuples are
immutable and thus, you can’t modify them after creating the same. The class ‘tuple’ represents the
tuple data type. You can create a tuple in Python simply by putting the items inside the parentheses
(). Subsequently, to separate the items stored in the tuple, you can use a comma (,).
For example,

// Empty tuple
my_tuple = ()
print("Initial empty tuple: ")
print(my_tuple)

// Tuple with strings

my_tuple = ('World', 'Peace')


print("\nTuple with the use of strings: ")
print(my_tuple)

// Tuple using a list

my_list = [1, 2, 4, 5, 6]
print("\nTuple using a list: ")
print(tuple(my_list))

//Tuple with nested tuples

nested_tuple1 = (0, 1, 2, 3)
nested_tuple2 = ('World', 'Peace')
nested_tuple3 = (nested_tuple1, nested_tuple2)
print("\nTuple with nested tuples: ")
print(nested_tuple3)

Output -

Initial empty tuple:


()

Tuple with the use of strings:


('World', 'Peace')

Tuple using a list:


(1, 2, 4, 5, 6)

Tuple with nested tuples:


((0, 1, 2, 3), ('World', 'Peace'))

6. Boolean Data Type

The boolean data type provides two built-in values, which are ‘True’ and ‘False’. These two
values help in determining if the given statement is true or false. Boolean objects that are true are
referred to as truthy (true), and false Boolean objects are referred to as falsy (false).

However, Python allows evaluating the non-Boolean objects in the Boolean context and
determining whether they are true or false. The class ‘bool’ represents the Boolean data type. A
non-zero value or “T” represents the True values, and zero or “F” represents the False values.

For example,
print(type(True))
print(type(False))
print(false)

Output -

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

7. Set Data Type

The set data type is an unordered collection of iterable, mutable, and unique data values.
Although the set contains various elements, the order of the elements remains unidentified. You can
create the set by using a built-in function set () in Python. In addition to this, a sequence of
elements is enclosed in the curly brackets {}, and the comma (,) is used to separate the elements.
The set can consist of various types of values.

For example,

// Empty set
set1 = set()

// Set with elements


set2 = {'Maria', 2, 3, 'Python'}

// Printing the set


print(set2)

// Add an element to the set


[Link](10)
print(set2)

// Remove an element from the set


[Link](2)
print(set2)

Output -

{'Maria', 2, 3, 'Python'}
{'Maria', 2, 3, 10, 'Python'}
{'Maria', 3, 10, 'Python'}

8. Dictionary Data Type

In Python, a dictionary data type is an unsorted set of key-value pairs. Informational values
can be stored using this data type. The dictionary data type is more efficient because it works like
an associative array or a hash table, where each key also stores a value. A colon (:) is used to
separate each key-value pair in the Dictionary, and a comma (,) is used to separate each key.

For example,
// Create a dictionary
my_dict = {1: 'Hi', 2: 'Hello', 3: 'Ohayo', 4: 'Bonjour'}

// Print the dictionary


print(my_dict)

// Accessing values using keys


print("1st word is " + my_dict[1])
print("2nd word is " + my_dict[4])

// Print the keys and values of the dictionary


print(my_dict.keys())
print(my_dict.values())

Output -

{1: 'Hi', 2: 'Hello', 3: 'Ohayo', 4: 'Bonjour'}


1st word is Hi.
2nd word is Hello
dict_keys([1, 2, 3, 4])
dict_values(['Hi', 'Hello', 'Ohayo', 'Bonjour'])

You might also like