In Python, data types are utilized to specify the type of data that a variable is capable of holding. They influence how data is stored and the operations that can be executed on that data. Python, as a dynamically typed language, enables developers to avoid explicitly declaring the data type of a variable; instead, it is automatically inferred based on the value assigned to it.
Let us take a look at the following example:
Example
# initializing a variable
var_1 = 10
# printing info
print(var_1) # printing value of var_1
print(type(var_1)) # printing data type of var_1
Output:
10
int
In this instance, we have not explicitly specified the data type for the variable, var1. Python has inferred the type of var1 to be 'int' automatically.
In this tutorial, we will explore the various data types utilized in Python, their applications, and additional insights.
Understanding the Data Types in Python
In Python, data types categorize various data items according to their attributes and functionalities. These data types signify the kinds of values that a variable can hold and the operations that can be executed on those values.
In Python, every element is treated as an object. From this perspective, we can view data types as classes, with variables serving as instances of these classes. There are several frequently utilized data types in Python:
| S. No. | Data Type | Examples |
|---|---|---|
1 |
Numeric Types | int,float,complex |
2 |
Sequence Types | str,list,tuple,range |
3 |
Set Types | set,frozenset |
4 |
Mapping Type | dict |
5 |
Boolean Type | bool |
6 |
Binary Types | bytes,bytearray,memoryview |
7 |
None Type | NoneType |
In the following sections, we are going to discuss about these Python data types in depth with the help of various examples.
Numeric Data Types
In Python, numeric data types serve the purpose of holding data in a numerical format. Numbers can be represented in various forms, which include integers, floating-point numbers, or complex numbers.
There are primarily three categories of numeric data types:
| S. No. | Numeric Data Type | Description |
|---|---|---|
1 |
int | Store signed integers of non-limited length |
2 |
float | Store floating decimal points and accurate up to 15 decimal places |
3 |
complex | Store complex numbers |
Let us these numeric data types in detail.
1. Integer (int)
An integer is defined as a complete number, which can be either positive, negative, or zero, and does not contain any decimal or fractional components. Examples of integers include 15, -7, 12, 0, -125, 268, among others. In Python, integer values are represented using the 'int' class. Notably, Python imposes no restrictions on the size of integer values; they can be of any magnitude and may extend up to the maximum memory capacity of the computer system.
Let us examine an example that demonstrates the process of declaring an integer in Python.
Example
# python program to show how to declare integers in Python
# initializing some variables with integers
var_1 = 16 # positive integer
var_2 = -21 # negative integer
var_3 = 0 # zero
# printing the types of initialized variables
print("Data Type of", var_1, "=", type(var_1))
print("Data Type of", var_2, "=", type(var_2))
print("Data Type of", var_3, "=", type(var_3))
Output:
Data Type of 16 = <class 'int'>
Data Type of -21 = <class 'int'>
Data Type of 0 = <class 'int'>
Explanation:
In the preceding code example, we initialized several variables with various integer values. Subsequently, we employed the type function to determine their data types and display this information to the user. Consequently, it is evident that all the defined variables are classified under the 'int' data type.
2. Floating-point (float)
A floating-point number refers to a numerical value that can either include a decimal point or be expressed using scientific notation. Examples of such numbers include 14.523, 3.14, and 1.5e3, among others. In Python, there exists a class named 'float' specifically designed for the storage of decimal values, which can be positive, negative, or zero. This class is capable of handling scientific notation (for instance, 1.6e4 is equivalent to 16000.0). The float class adheres to the IEEE 754 floating-point standard and offers a precision limit of up to 15 decimal places.
Let’s examine an example that demonstrates the process of declaring a float variable in Python.
Example
# python program to show how to declare floating-point numbers in Python
# initializing some variables with floating-point numbers
var_1 = 1.72 # positive float
var_2 = -0.05 # negative float
var_3 = 0.0 # zero as a float
var_4 = 1.6e4 # scientific notation
# printing the types of initialized variables
print("Data Type of", var_1, "=", type(var_1))
print("Data Type of", var_2, "=", type(var_2))
print("Data Type of", var_3, "=", type(var_3))
print("Data Type of", var_4, "=", type(var_4))
Output:
Data Type of 1.72 = <class 'float'>
Data Type of -0.05 = <class 'float'>
Data Type of 0.0 = <class 'float'>
Data Type of 16000.0 = <class 'float'>
Explanation:
In the code snippet provided above, several variables have been assigned float values. Following this, we utilized the type function to retrieve the data types of these variables and display them for the user’s reference. Consequently, we can see that all the variables that were initialized are classified under the 'float' type.
3. Complex Numbers (complex)
A Complex Number is defined as a number that comprises both a real component and an imaginary component. It is expressed in the following format:
a + bj
where:
- a = It is the real part. It can either a float or integer.
- b = It is the imaginary part. It can either a float or integer.
- j = it represents √(-1). It is an imaginary unit used in Python.
In Python, complex numbers are encapsulated within a class referred to as 'complex'.
Let us take a look at an example that demonstrates how to define a complex number in Python.
Example
# python program to show how to declare complex numbers in Python
# initializing some variables with complex numbers
var_1 = 3 + 5j # where 2 is the real part and 5 is the imaginary part
var_2 = -3.4 + 2.8j
var_3 = -5 - 1.9j
var_4 = -6 + 0j
# printing the types of initialized variables
print("Data Type of", var_1, "=", type(var_1))
print("Data Type of", var_2, "=", type(var_2))
print("Data Type of", var_3, "=", type(var_3))
print("Data Type of", var_4, "=", type(var_4))
Output:
Data Type of (3+5j) = <class 'complex'>
Data Type of (-3.4+2.8j) = <class 'complex'>
Data Type of (-5-1.9j) = <class 'complex'>
Data Type of (-6+0j) = <class 'complex'>
Explanation:
In the code snippet provided above, several variables have been initialized with complex numbers. Subsequently, the type function has been employed to determine their data types, which are then printed for user visibility. Consequently, it can be noted that all the initialized variables are classified under the 'complex' type.
Sequence Data Types
In Python, sequence data types serve the purpose of storing multiple elements in a structured, ordered format. The primary sequence data types available in Python can be categorized into three main types:
| S. No. | Sequence Data Type | Description |
|---|---|---|
1 |
list | Ordered, mutable, and heterogeneous collection of elements |
2 |
tuple | Ordered, and immutable collection of elements |
3 |
str | Sequence of characters |
S. No.
Sequence Data Type
Description
A collection of elements that is ordered, allows for modification, and consists of varied data types.
tuple
Ordered, and immutable collection of elements
Sequence of characters
Let us these sequence data types in detail.
1. Lists (list)
Comparable to arrays in various programming languages, a List in Python serves as an ordered collection of data items. It can contain elements of varying data types, separated by commas. Lists possess mutable characteristics, which allows for the modification of their elements at any moment.
Let's examine an illustration that shows how to create a list in Python:
Example
# simple python program to show how to initialize a list
# creating a list
list_1 = [1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome'] # different types of elements
# printing details
print("Initialized List:", list_1) # printing elements of the list
print("Data Type:", type(list_1)) # printing data type
Output:
Initialized List: [1, 0.5, 'hello', (1+5j), 170.0, -12, 'welcome']
Data Type: <class 'list'>
Explanation:
In the code snippet presented above, a list has been created containing various items of different data types. Subsequently, the list has been displayed for the user's reference, and the type function has been utilized to retrieve and display the types of these items. Consequently, we can see that the list created can accommodate multiple data types at once and is classified as an instance of the 'list' class.
3. Tuples (tuple)
Tuples are collections of data elements arranged in a specific order, similar to lists. The primary distinction between the two is that tuples possess an immutable characteristic. This implies that once a tuple is formed, its elements cannot be altered.
In Python, we utilize parentheses '' to create a tuple that holds multiple elements. Below is an example illustrating how to initialize a tuple in Python:
Example
# simple python program to show how to initialize a tuple
# creating a tuple
tuple_1 = (1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome') # different types of elements
# printing details
print("Initialized tuple:", tuple_1) # printing elements of the tuple
print("Data Type:", type(tuple_1)) # printing data type
Output:
Initialized tuple: (1, 0.5, 'hello', (1+5j), 170.0, -12, 'welcome')
Data Type: <class 'tuple'>
Explanation:
In the code snippet provided above, a tuple has been created containing various items of differing data types. Following this, the tuple is printed for reference, and the type function is utilized to retrieve their respective types, which are then displayed for the users. Consequently, it is evident that the defined tuple is capable of holding multiple data types at once and is classified under the 'tuple' class.
3. String (str)
A String is defined as a series of characters that are contained within either single (') or double (") quotation marks. Like Tuples, strings are inherently immutable. In Python, strings are implemented through the 'str' class.
Let’s explore an example that illustrates the process of initializing a string in Python:
Example
# simple python program to show how to initialize string
# initializing variables with some string
str_1 = 'Example'
str_2 = 'I love learning Python from C# Tutorial'
# printing details
print("String 1 :", str_1) # printing string
print("Data Type of String 1:", type(str_1)) # printing data type
print("String 2 :", str_2) # printing string
print("Data Type of String 2:", type(str_2)) # printing data type
Output:
String 1 : C# Tutorial
Data Type of String 1: <class 'str'>
String 2 : I love learning Python from C# Tutorial
Data Type of String 2: <class 'str'>
Explanation:
In the code snippet presented above, two variables named str1 and str2 have been created and assigned specific text values. Following this, we printed the content of these strings and utilized the type function to determine their data types, which were then displayed for the users. Consequently, the output indicates that the printed strings are of the 'str' class.
4. Range (range)
Furthermore, there exists another category within the sequence data type. This specific data type is referred to as range. In Python, a range is an object utilized to signify a sequence of numerical values.
Let us examine an illustration that demonstrates how to initialize a range in Python.
Example
# simple python program to show how to initialize a range
# creating a range
r = range(3, 26, 2)
# printing the results
print("Range:", r) # printing range
print("Range as List:", list(r)) # printing range as a list
print("Data Type:", type(r)) # printing data type
Output:
Range: range(3, 26, 2)
Range as List: [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
Data Type: <class 'range'>
Explanation:
In the code snippet provided above, the range function is utilized to generate a sequence starting from 3 up to 26, with an increment of 2. Following this, we have printed the range for clarity. Additionally, we have converted the range into a list to showcase all the elements within the produced sequence. Finally, we have displayed its data type. Consequently, it can be noted that it is classified under the 'range' type.
Set Data Types
In Python, Set Data Types are utilized to maintain unordered groups of distinct elements.
In general, there are two categories that fall under the umbrella of set data types.
| S. No. | Set Data Type | Description |
|---|---|---|
1 |
set | Unordered, unique, mutable, and unindexed collection of elements |
2 |
frozenset | Unordered, unique, immutable, and unindexed collection of elements |
Let us these set data types in detail.
1. set
In Python, a set is characterized as an unordered, mutable, and unindexed collection of distinct data elements. Sets are advantageous for holding unique values and can execute a range of mathematical operations such as union, intersection, and difference.
To establish a set in Python, we can utilize either curly braces {} or the set function. Below is an example that demonstrates the various methods for initializing sets in Python.
Example
# simple python program to show how to initialize a set
# creating sets
set_1 = {"mango", "apple", "orange", "banana"} # using {}
set_2 = set(["ginger", "lemon", "potato", "tomato"])
# printing the results
print("Set 1:", set_1) # set 1
print("Data type of Set 1:", type(set_1)) # data type of set 1
print("Set 2:", set_2) # set 2
print("Data type of Set 2:", type(set_2)) # data type of set 2
Output:
Set 1: {'mango', 'orange', 'banana', 'apple'}
Data type of Set 1: <class 'set'>
Set 2: {'lemon', 'tomato', 'potato', 'ginger'}
Data type of Set 2: <class 'set'>
Explanation:
In the preceding example, two sets were created employing distinct methods. The first set was defined using curly braces {} while the second set utilized the set constructor for its initialization. Following this, we displayed the elements of each set along with their respective data types. Consequently, it is evident that both sets are instances of the 'set' class.
2. frozenset
In Python, there exists a function named frozenset that generates a frozenset object. This particular object is characterized as an immutable and unordered data structure. A frozenset is composed of distinct elements, which aligns it with the set data type; nevertheless, it possesses the unmodifiable nature akin to that of tuples.
Let us examine an example that demonstrates how to create a frozenset in Python.
Example
# simple python program to show how to create a frozeset
# creating an iterable
list_1 = ["berries", "orange", "mango", "apple"] # a list
# using the frozenset() function to create a frozenset object
f_1 = frozenset(list_1)
# printing results
print("Frozenset:", f_1) # frozenset
print("Data Type:", type(f_1)) # data type
Output:
Frozenset: frozenset({'mango', 'orange', 'berries', 'apple'})
Data Type: <class 'frozenset'>
Explanation:
In the preceding example, we initialized a list to serve as an iterable. Subsequently, we employed the frozenset function, providing the list as an argument. We then displayed the resulting object alongside its data type. Consequently, we can confirm that the frozenset object was created successfully and it is categorized under the 'frozenset' class.
Mapping Data Type - Dictionary (dict)
In Python, elements can be stored in pairs of keys and values through the use of Dictionaries. A Dictionary serves as an ordered collection of items where each value is linked to a unique identifier.
Let us examine an instance of how to initialize a dictionary in Python.
Example
# simple python program to show how to create a dictionary
# creating a dictionary
person_1 = {
'name' : 'Mark',
'age': '25',
'gender' : 'Male',
}
# printing results
print("Person Details:\n", person_1) # dictionary
print("Data Type:", type(person_1)) # its data type
Output:
Person Details:
{'name': 'Mark', 'age': '25', 'gender': 'Male'}
Data Type: <class 'dict'>
Explanation:
In the preceding example, we established a dictionary and displayed its data type for clarity. In this case, 'name', 'age', and 'gender' serve as the keys, with their corresponding values being 'Mark', '25', and 'Male', respectively.
Boolean Data Type (bool)
The Boolean data type is a fundamental built-in type in Python that consists of two constant values:
- True: The Boolean value 'True' signifies 1 and is produced when an expression or object is evaluated as true.
- False: The Boolean value 'False' represents 0 and is generated when an expression or object is deemed false.
In Python, it is possible to assess non-Boolean entities within a Boolean framework, categorizing them as either True or False. The 'bool' class is utilized for the purpose of storing Boolean objects.
Note: Python is case-sensitive; therefore, it will return error if the Boolean values (True and False) is passed in lowercase (e.g., true, false).
Let's examine an instance of the Boolean data type in Python.
Example
# simple python program to show the Boolean data types
# initializing variables
a = True
b = False
# c = true <= Will Return Error
# printing the results
print("Value of a:", a)
print("Data Type of a:", type(a))
print("Value of b:", b)
print("Data Type of b:", type(b))
# print("Value of c:", c)
# print("Data Type of c:", type(c))
Output:
Value of a: True
Data Type of a: <class 'bool'>
Value of b: False
Data Type of b: <class 'bool'>
Explanation:
In the preceding example, two variables - a and b - were initialized with the respective values of True and False. We subsequently printed these variables for clarity and employed the type function to ascertain their data types. Consequently, it is evident that both variable a and variable b are instances of the 'bool' class.
Binary Data Types
Python provides binary data types designed specifically for managing raw binary data. The following are these data types:
| S. No. | Binary Data Type | Description |
|---|---|---|
1 |
bytes | Immutable sequence of bytes |
2 |
bytearray | Mutable sequence of bytes |
3 |
memoryview | Efficient access to binary data |
Let us these binary data types in detail.
1. bytes
The bytes data type represents an unchangeable sequence of bytes, with each byte having a value that spans from 0 to 255. This type is particularly beneficial for handling binary files, facilitating network communication, or performing cryptographic operations.
Let us examine an instance of the bytes data type in Python.
Example
# simple python program to show the creation of bytes object
# creating bytes using a list of integers (0-255)
obj_1 = bytes([78, 79, 80, 81, 82]) # ASCII values
# printing results
print("Value of Object 1:", obj_1)
print("Data Type of Object 1:", type(obj_1))
Output:
Value of Object 1: b'NOPQR'
Data Type of Object 1: <class 'bytes'>
Explanation:
In the preceding example, the bytes function has been employed to generate a byte object from the collection of integers: 78, 79, 80, 81, and 82 in that order. Following this, we displayed the created object alongside its data type. Consequently, it is evident that the value of the object appears as b'NOPQR', which is classified under the 'bytes' type.
2. bytearray
In contrast to bytes, the bytearray data type represents a mutable sequence of bytes that enables in-place alterations to binary data.
To instantiate an object from the bytearray class, one must provide a specified iterable as an argument to the built-in bytearray function.
Let us examine an illustration of the bytearray data type available in Python.
Example
# simple python program to show the creation of bytearray object
# creating a bytearray object using a list of integers
obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
# printing results
print("Value of Object 1:", obj_1)
print("Data Type of Object 1:", type(obj_1))
Output:
Value of Object 1: bytearray(b'NOPQR')
Data Type of Object 1: <class 'bytearray'>
Explanation:
In the preceding illustration, the bytearray function is utilized to generate a bytearray object derived from the integer list - 78, 79, 80, 81, and 82. Following this, we displayed the initialized object along with its corresponding type. Consequently, we can see that the object’s value is represented as b'NOPQR', which is classified under the 'bytearray' class.
3. memoryview
The memoryview data type serves as a streamlined and effective means to access binary data without the need for duplication. This particular data type proves to be advantageous for handling substantial data operations where performance is a critical factor.
Let us examine an instance of the memoryview data type available in Python.
Example
# simple python program to show the creation of bytearray object
# creating a bytearray object using a list of integers
obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
# creating a memoryview object
obj_2 = memoryview(obj_1)
# printing results
print("Value of Object 2:", obj_2)
print("Data Type of Object 2:", type(obj_2))
Output:
Value of Object 2: <memory at 0x7ebcf57bf640>
Data Type of Object 2: <class 'memoryview'>
Explanation:
In the preceding example, the bytearray function has been utilized to generate a bytearray object from a list of integers: 78, 79, 80, 81, and 82. Following this, the memoryview function was employed to transform the bytearray object into a memoryview object. We subsequently displayed the value of this object along with its type. Consequently, it is evident that the value of the object is represented as <memory at 0x7ebcf57bf640>, and it is classified under the 'memoryview' category.
None Data Type (NoneType)
Python includes a unique data type referred to as NoneType. This type contains a singular value: None. It is utilized to signify absent values, return values from functions, and as placeholders within Python.
To instantiate an object of the NoneType class, one can effortlessly assign the value None to a variable during initialization.
Let us examine the subsequent example that illustrates the purpose of the 'NoneType' class.
Example
# simple python program to show the creation of NoneType object
# initializing a variable with None
var_1 = None
# printing results
print("Value of var_1:", var_1)
print("Data Type of var_1:", type(var_1))
Output:
Value of var_1: None
Data Type of var_1: <class 'NoneType'>
Explanation:
In the example provided, a variable named var1 has been assigned the value of None. Subsequently, we printed this variable for our reference and employed the type function to determine its data type. Consequently, we can see that the variable var1 holds the value None, and it is classified under the 'NoneType' category.
Type Casting in Python
Python is a language with dynamic typing, which means we are not required to explicitly specify the data types for our variables. Nevertheless, Python provides the capability to transform one data type into a different one as needed.
The procedure of transforming one data type into a different one is referred to as Type Casting. In Python, there are two methods available for casting variables:
- Implicit Type Casting (Automatic): Python autonomously converts smaller data types into larger counterparts.
Example
# python program to show implicit type casting
# initializing some variables
p = 6 # int
print(p, "=>", type(p))
q = 3.7 # float
print(q, "=>", type(q))
# adding variable p and q and storing their results
r = p + q # int + float = float
# printing results
print(p, '+', q, '=', r)
print(r, "=>", type(r))
Output:
6 => <class 'int'>
3.7 => <class 'float'>
6 + 3.7 = 9.7
9.7 => <class 'float'>
Explanation:
In the preceding example, we initialized two variables, p and q, which are of distinct types (int and float). Following this, we performed an addition operation on these variables and assigned the resultant sum to another variable, r. Subsequently, we displayed the data types of these variables. Consequently, we can see that r undergoes an implicit conversion to 'float'.
- Explicit Type Casting (Manual): Developers utilize Python's built-in functions to convert one data type to another.
Example
# python program to show explicit type casting
# converting int to float
p = float(14)
print(p)
# converting float to int
q = int(7.52)
print(q)
# converting string to int
r = int("7295")
print(r)
# converting list to tuple
list_1 = [4, 7, 10]
tuple_1 = tuple(list_1)
print(type(list_1))
print(type(tuple_1))
Output:
14.0
7
7295
<class 'list'>
<class 'tuple'>
Explanation:
In the preceding example, we have utilized several built-in functions such as float, int, and tuple to transform the data type of the provided variable into the desired data type.
For further information regarding Type Casting, please refer to: Python - Type Casting.
Conclusion
Grasping the various data types in Python is crucial for crafting efficient code. These intrinsic data types empower developers to store and manage different forms of data both effectively and efficiently. Achieving proficiency in these types will enhance programming techniques and improve problem-solving abilities.
Python Data Types - MCQs
- What will the result be when executing the subsequent code?
q = 7
print(type(q))
- <class 'float'>
- <class 'str'>
- <class 'int'>
- <class 'list'>
Response: C) <class 'int'>
- What is the type of data represented by the variable below?
p = 62.5
- float
- complex
- bool
- Which of the following is a mutable data type in Python?
- tuple
- list
- frozenset
Clarification: Lists possess mutability, indicating that they can be altered subsequent to their creation.
- What will the result be when executing the following code?
x = 3 + 4j
print(type(x))
- <class 'float'>
- <class 'int'>
- <class 'complex'>
- <class 'tuple'>
- What is the correct syntax to create a set in Python?
- {5, 4, 3}
- [5, 4, 3]
- (5, 4, 3)
- set[5, 4, 3]
Clarification: Curly braces {} serve to establish a set, with the exception of generating an empty set, which necessitates the use of set.