Python DataTypes
Python is a dynamically-typed programming language, meaning that the data type of a variable is
inferred automatically based on
the value assigned to it. Python supports various data types to represent different kinds of values.
Python has several built-in data types, that can be broadly categorized into the following categories:
- Numeric Types
- Sequence Types
- Mapping Types
- Set Types
- Boolean Types
- Binary Types
- None Types
Understanding these different categories of data types in Python is important for writing effective and efficient code. Each category of
data
type has its own set of operations and methods, which can be used to manipulate and process the data.
Let's see them in detail.
Numeric Datatype :
Numeric data types are used to represent numbers in Python. There are three main types of numeric data types in Python:
Sl. No. | Classification | Description | Usage Example (in IDLE) |
---|---|---|---|
1 | Integer | Integers are whole numbers and have no decimal points. They can be positive, negative, or zero. |
x = 10 y = -5 z = 0 |
2 | Floating-point Number |
Floating-point numbers represent real numbers and have decimal points. They are useful for representing fractional values and for performing mathematical operations. |
a = 3.14 b = -2.5 c = 0.0 |
3 | Complex Number |
Complex numbers represent a number with a real and imaginary part. They are often used in mathematical and scientific computations. |
d = 2 + 3j e = -4j f = 1.5 - 2.8j |
In addition to these three main numeric data types, Python also supports the following numeric types:
- Long integers: Long integers are used to represent very large integers that cannot be represented by regular integers.
- Booleans: Booleans are used to represent truth values. They can be either True or False.
Numeric data types in Python support a range of arithmetic and logical operations, including addition, subtraction, multiplication,
division, and more.
Python also provides several built-in functions for working with numeric data types, such as abs(), round(), and
pow().
Understanding numeric data types and their operations is essential for performing mathematical computations and working
with scientific data in Python.
Sequence Datatype :
Sequence data types in Python are used to represent a collection of elements in a specific order. There are three main sequence data types
in Python:
Sl. No. | Classification | Description | Usage Example (in IDLE) |
---|---|---|---|
1 | Strings | Strings are used to represent a sequence of characters. They can be defined using single quotes ('...') or double quotes ("..."). |
x = 'Hello, World!' y = "Python is awesome" |
2 | Lists |
Lists are used to represent a sequence of values of any type. They are defined using square brackets [ ] and the values are separated by commas. |
a = [1, 2, 3, 4, 5] b = ['apple', 'banana', 'cherry'] |
3 | Tuples |
Tuples are similar to lists, but they are immutable, which means that their contents cannot be modified after they are created. They are defined using parentheses ( ) and the values are separated by commas. |
p = (1, 2, 3) q = ('red', 'green', 'blue') |
Sequence data types in Python support a range of operations and methods, including indexing, slicing, concatenation, and more. For example,
we can access individual elements of a sequence using indexing:
print(x[0]) # Output: H
print(a[2]) # Output: 3
print(p[1]) # Output: 2
We can also slice a sequence to get a subset of its elements:
print(x[0:5]) # Output: Hello
print(a[1:4]) # Output: [2, 3, 4]
print(q[:2]) # Output: ('red', 'green')
Understanding sequence data types and their operations is essential for working with collections of data in Python, such as text processing, data analysis, and more.
Mapping Datatype :
Mapping data type in Python is used to store data in the form of key-value pairs. It provides an efficient way to access and manipulate data
using a unique key. The main mapping data type in Python is a dictionary.
A dictionary is defined using curly braces { } and the key-value pairs are separated by commas. The keys must be unique and can be of any
immutable data type such as strings, numbers, or tuples. The values can be of any data type, including other dictionaries. Here is an example
of how to create a dictionary:
# create a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
In the above example, we created a dictionary named my_dict with three key-value pairs. The key name has the value 'John', the key age has the value of
30, and the key gender has the value 'Male'.
We can access the values of a dictionary by using the keys. For example, to get the value of the key name from the dictionary my_dict, we can use
the following code:
print(my_dict['name']) # Output: John
We can also add or modify key-value pairs in a dictionary. For example, to add a new key-value pair to my_dict, we can use the following code:
my_dict['city'] = 'New York'
This code will add a new key 'city' with the value 'New York' to the dictionary my_dict. Dictionaries also support various built-in methods to manipulate their content, such as .keys(), .values(), and .items(), among others. Understanding mapping data types and their operations is essential for working with complex data structures in Python.
Set Datatype :
In Python, a set is an unordered collection of unique elements. The set data type is defined using curly braces { } or using the set() function. For example:
# create a set
my_set = {1, 2, 3, 4, 5}
# create a set using set() function
another_set = set([3, 4, 5, 6, 7])
In the above example, we created two sets my_set and another_set. my_set contains the elements 1, 2, 3, 4, and 5, while another_set contains the elements
3, 4, 5, 6, and 7.
Sets in Python support a range of operations and methods, including union, intersection, difference, and more. For example, we can perform
the union operation on two sets using the '|' operator, as follows:
# union of two sets
union_set = my_set | another_set
print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7}
Similarly, we can perform the intersection operation using the & operator, as follows:
# intersection of two sets
intersection_set = my_set & another_set
print(intersection_set) # Output: {3, 4, 5}
Sets are also useful for removing duplicates from a list or any other iterable object. We can convert an iterable object to a set using the set() function
and then convert it back to a list to remove duplicates. For example:
# intersection of two sets
intersection_set = my_set & another_set
print(intersection_set) # Output: {3, 4, 5}
Understanding sets and their operations are essential for working with collections of data in Python, such as data cleaning, data preprocessing, and more.
Boolean Datatype :
Boolean data type in Python is used to represent two values: True and False. It is primarily used for logical operations, such as conditional statements and loops.
Boolean values are created using the keywords True and False, which are case-sensitive. For example:
# boolean values
x = True
y = False
Boolean values can also be the result of a comparison operation. For example:
# comparison operations
a = 5
b = 7
c = (a < b) # c will be True
d = (a > b) # d will be False
In Python, the boolean data type is a subclass of the integer data type, where True is equivalent to 1 and False is equivalent to 0. Boolean
values are often used in conditional statements, such as if, elif, and else, to control the flow of a program. For example:
# conditional statement
x = 5
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Understanding boolean data type and its operations is essential for working with logical operations and conditional statements in Python.
Binary Datatype :
Binary data type in Python is used to represent binary data, such as bytes and byte arrays. Binary data is a sequence of 8-bit bytes,
where each byte represents a value between 0 and 255. Binary data is often used for encoding and decoding of data, such as images, videos,
and other multimedia files.
In Python, binary data is represented using bytes and byte arrays. Bytes are immutable objects, whereas byte arrays are mutable objects.
Bytes are created using the b prefix before a string literal, as follows:
# create bytes object
my_bytes = b"hello world"
Byte arrays, on the other hand, are created using the bytearray() function, as follows:
# create byte array object
my_bytearray = bytearray(b"hello world")
We can access individual bytes in a bytes object or byte array using indexing, as follows:
# access bytes in a bytes object or byte array
my_bytes = b"hello world"
print(my_bytes[0]) # Output: 104
print(my_bytearray[0]) # Output: 104
Binary data can also be converted to other data types, such as integers and strings, using built-in functions. For example:
# convert binary data to integers and strings
my_bytes = b"\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64"
my_int = int.from_bytes(my_bytes, byteorder='big')
my_str = my_bytes.decode('utf-8')
print(my_int) # Output: 7064260253300774244
print(my_str) # Output: Hello World
Understanding binary data type and its operations is essential for working with binary data in Python, such as encoding and
decoding of data, and other low-level operations.
None Datatype :
The None data type in Python is used to represent the absence of a value or a null value. It is commonly used as a placeholder
or a default value for variables, arguments, and function returns.
The None keyword is used to create a None object, as follows:
# create a None object
my_variable = None
None is often used to initialize a variable before it is assigned a value or to indicate that a variable has no value. For example:
# initialize a variable with None
my_variable = None
# assign a value to the variable later
my_variable = 5
# use the variable in a conditional statement
if my_variable is not None:
print("my_variable has a value")
else:
print("my_variable is None")
None is also often used as a default value for function arguments, as follows:
# function with a default argument value of None
def my_function(arg1=None):
if arg1 is not None:
print("arg1 has a value")
else:
print("arg1 is None")
When a function returns no value, it returns None by default. For example:
# function with no return value
def my_function():
print("This function has no return value")
# call the function and assign the return value to a variable
my_variable = my_function()
print(my_variable) # Output: None
Understanding the None data type and its usage is essential for handling null values and default values in Python.