Python data types are crucial for writing efficient and effective code. The type of data determines the operations that can be performed on it, the values it can store, and the ways in which it is stored and manipulated. In this article, we will learn various data types in Python, exploring their features and use cases.
Table of contents
What are Data Types in Python?
A data type is a classification of data that defines the possible values that an object can take, the operations that can be performed on that object, and the way in which the object is stored in memory.
They are important because they help ensure that programs handle data in a consistent and predictable manner, which can lead to fewer errors and more efficient code.
Categories of Python Data Types
In Python, there are a variety of built-in data types that can be used to represent different kinds of data. Understanding these data types and their features is important for writing effective and efficient Python code.
There are several categories of built-in data types that you can use to store and manipulate data. These categories include:
Type Category | Description |
---|---|
Numeric Type | Numerics in Python include integers, floats, and complex numbers. |
Character Type | String |
Sequence Type | The sequence in Python includes lists, tuples, and ranges. |
Mapping Type | The mapping in Python is the dictionary, which allows you to store key-value pairs. |
Set Type | The set and frozenset in Python allow you to store a collection of unique items. |
Boolean Type | The boolean in Python represents logical values True and False. |
Binary Type | Binary in Python includes bytes, bytearray, and memoryview. |
None Type | The NoneType in Python represents the absence of a value. |
Below is the complete list of python Data types:
1. Integer
An integer is one of the basic built-in data types in python. An integer is a whole number without a decimal point. It can be positive, negative, or zero. Integers support all of the standard mathematical operations, including addition, subtraction, multiplication, and division.
Integers in Python can range from -2^31
to 2^31-1
, or from -2^63
to 2^63-1
for 64-bit systems. In Python, you can create an integer by simply assigning a whole number to a variable.
For example:
# Positive value
x = 5
# Negative value
y = -10
# Zero value
z = 0
2. Float
A float in Python is a number that has a decimal point, or a number written in scientific notation. In Python, you can create a float by simply assigning a number with a decimal point to a variable. Floats in Python can represent a wide range of values, from approximately 1.7 × 10^308
to 5.0 × 10^-324
.
Floating-point numbers may not always be precise due to the way they are represented in a computer.It is generally not recommended to compare floats for equality directly, but rather to check if the difference between two floats is less than a small tolerance value.
# Float Positive value
x = 3.14
# Float Negative value
y = -2.5
# Float Exponential Value
z = 1.23e-4.
3. Complex
Complex Number in python is represented using the complex data type. A complex number is a number that has a real part and an imaginary part, written in the form a + bj, where a is the real part, b is the imaginary part, and j is the square root of -1.
Python Provides built-in functions for working with complex numbers, such as abs()
, conjugate()
, and real()
. Complex numbers in Python can represent a wide range of values, both real and imaginary.
# Complex type
x = 3 + 4j
y = -2.5 + 1.2j
z = complex(2, -3)
4. String
Python String data type is a sequence of characters that is used to represent text. Strings are represented using single quotes (‘…’) or double quotes (“…”).
To create a string in Python, simply enclose a sequence of characters in single quotes or double quotes. Strings in Python can represent any sequence of characters, including letters, numbers, punctuation, and whitespace.
my_string = 'I am a String'
5. List
A list is a collection of items that are ordered and changeable. In Python, list data types are represented using square brackets [] and each item in the list is separated by a comma.
To create a list in Python, enclose a sequence of values in square brackets, separated by commas. Lists in Python can hold any data type, including integers, floats, strings, and other lists. They can be empty, or they can contain any number of items.
# List example
my_list = [1, 2, 3, 4, 5]
6. Tuple
A tuple is a Python data type that is similar to a list in that it is an ordered collection of values. However, unlike lists, tuples are immutable, which means that their values cannot be changed once they are created. Tuples are represented using parentheses ().
To create a tuple in Python, enclose a sequence of values in parentheses, separated by commas. Like lists, tuples in Python can hold any data type, including integers, floats, strings, and other tuples.
# Tuple example
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
7. dict – Python Dictionary
A dictionary is a built-in Python data type that is used to store key-value pairs. Each key in a dictionary must be unique and is used to retrieve the corresponding value.
They are represented using curly braces {}. To create a dictionary in Python, enclose a comma-separated list of key-value pairs in curly braces, with a colon between the key and value.
# Dictionary example
my_dict = {'name': 'Ali', 'city': 'Delhi'}
print(my_dict['name'])
# Output: Ali
8. Set
A set data type is an unordered collection of unique elements in Python. It is a built-in data type and is represented by curly braces {}. Sets can be used to perform mathematical set operations like union, intersection, difference, etc.
To create a set in Python, you can use curly braces {} or the set() function. Set is useful when you need to perform mathematical set operations like union, intersection, and difference on collections of unique elements.
# Set example
my_set = {1, 2, 3, 4}
my_set = set([1, 2, 3, 4])
9. boolean
The Boolean data type in Python represents one of two possible values, either True or False. It is used to express logical values, and is a built-in data type in Python.
In Python, the Boolean values are represented by the keywords True and False. You can assign these values to a variable like this:
# Boolean example
x = True
y = False
Use the Boolean data type in Python:
a = 10
b = 20
c = a > b
print(c)
10. Byte
The byte data type in Python is used to represent a group of 8 binary digits. It is a built-in data type in Python that is used for working with binary data.
A byte in Python can hold any value from 0 to 255. It is typically used to represent binary data, such as images or audio files, or to work with low-level network protocols.
The byte data type is a built-in data type in Python that is used to work with binary data. It is often used in conjunction with other data types, such as strings, to manipulate binary data.
# Byte example
x = b"hello world"
print(x)
11. byte array
The bytearray data type in Python is a mutable sequence of bytes. It is a built-in data type in Python that is used for working with binary data.
It is often used in conjunction with other data types, such as strings, to manipulate binary data. Bytearrays are similar to bytes, but unlike bytes, they can be modified in place.
It is used to represent data in low-level network protocols, and are also used in data serialization and deserialization.
# Byte array
x = bytearray(b"hello world")
x[0] = 74
print(x)
# Output
# bytearray(b'Jello world')
12. Memory View
Memory View allows you to view the memory of an object without creating a copy of it, making it useful for working with large data sets. The memoryview in Python is a built-in class that provides a way to access the internal memory of an object that supports the buffer protocol.
The memoryview provides a way to access the memory of an object without creating a copy of it. This can be useful for working with large data sets, as it allows you to access the data in a more efficient manner.
Memoryview objects are read-only, but they can be used to slice and manipulate the memory of an object. Memoryview objects are often used in conjunction with the array module to manipulate large arrays of data.
# memory view
x = bytearray(b"hello world")
m = memoryview(x)
print(m[2:9])
# Output:
# memory at 0x0000022667F9DA80
13. NoneType
In Python, the NoneType data type represents the absence of a value. It is a built-in type that has only one value: None. The NoneType data type is not typically used in Python code as a variable type. Instead, it is used to indicate the absence of a value, for example as a default value for a function argument.
The NoneType data type is often used in Python code to represent the absence of a value, for example as a default value for a function argument.
It is also commonly used to indicate that a function or method does not return a value, since functions that do not explicitly return a value will return None
by default. In Python, None
is often used in conditional statements to test whether a variable has been assigned a value or not.
def greet(name=None):
if name:
print(f"Hello, {name}!")
else:
print("Hello, world!")
What is type conversion in Python?
It is often necessary to convert a variable from one data type to another. This process is known as type conversion or type casting. Python provides built-in functions for converting data types.
# int() function
x = int(5.5)
print(x)
# Output: 5
# float() function
y = float(2)
print(y)
# Output: 2.0
# str() function
a = str(10)
print(a)
# Output: '10'
# list() function
b = list((1, 2, 3))
print(b)
# Output: [1, 2, 3]
Summary and Conclusion
We have discussed different Python data types. You will now be able to the right data types for storing data in your program. I hope this article has provided a useful overview of the different data types in Python and how to work with them.
Happy coding!