
What are Data Types in Python?
In Python, data types define the kind of data a variable can hold. Understanding the various data types is essential for writing efficient and error-free code. Python supports several built-in data types, each serving a specific purpose. Here are the primary categories:
1. Numeric Types
- int: Represents integers (whole numbers) without decimal points. Example:
5
, -42
, 1000
.
- float: Represents floating-point numbers (decimals). Example:
3.14
, -0.001
, 2.0
.
- complex: Represents complex numbers with a real and imaginary part. Example:
2 + 3j
, -1 + 4j
.
2. Sequence Types
- list: An ordered, mutable collection of elements. Lists can hold elements of different data types. Example:
[1, 2.5, "hello"]
.
- tuple: Similar to a list, but immutable (cannot be changed after creation). Example:
(1, 2, 3)
.
- range: Represents a sequence of numbers, commonly used in loops. Example:
range(0, 5)
.
3. Text Type
- str: Represents strings (sequences of characters). Strings are immutable in Python. Example:
"hello"
, 'Python'
.
4. Mapping Type
- dict: A collection of key-value pairs. Keys are unique, and values can be any data type. Example:
{"name": "Alice", "age": 25}
.
5. Set Types
- set: An unordered collection of unique elements. Example:
{1, 2, 3}
.
- frozenset: Like a set, but immutable. Example:
frozenset([1, 2, 3])
.
6. Boolean Type
- bool: Represents a Boolean value, either
True
or False
. Example: True
, False
.
7. Binary Types
- bytes: Immutable sequence of bytes. Example:
b'hello'
.
- bytearray: Mutable sequence of bytes. Example:
bytearray([65, 66, 67])
.
- memoryview: A view object that exposes an array’s buffer interface.
Each of these data types is integral to writing Python programs, as they allow for efficient storage, manipulation, and retrieval of data.