Python Data Types
In programming, data types are an important concept. Variables can store data of different types, and different types can perform different operations. Python has multiple built-in data types, mainly classified into the following categories:
Core Data Types
| Type Name | Type Alias | Example | Description |
|---|---|---|---|
| Text Type | str | "Hello", 'Python' | Used to store text, composed of a series of characters. |
| Numeric Type | int | 10, -50 | Integers. |
float | 3.14, -0.01 | Floating point numbers (i.e., decimal). | |
complex | 1+2j | Complex numbers. | |
| Sequence Type | list | [1, "apple", 3.0] | Lists, ordered and modifiable collections. |
tuple | (1, "apple", 3.0) | Tuples, ordered but immutable collections. | |
range | range(6) | Represents an immutable numeric sequence. | |
| Mapping Type | dict | {"name": "John", "age": 30} | Dictionaries, unordered key-value pair collections. |
| Set Type | set | {"apple", "banana"} | |
| Frozen Set Type | frozenset | frozenset({"a", "b"}) | |
| Boolean Type | bool | True, False | Represents true or false. |
| Binary Type | bytes, bytearray, memoryview | b"Hello" | Used to process binary data. |
| None Type | NoneType | None | Represents an empty value or non-existent value. |
Getting Variable Type
You can use the built-in type() function to check the data type of any variable.
x = 5
y = "Hello, World!"
z = [1, 2, 3]
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'list'>Python is Dynamically Typed
Python is a dynamically typed language. This means you don't need to specify the variable's type when declaring it; the interpreter automatically infers it at runtime. This makes development more flexible and fast.
my_var = 100 # At this point, my_var is int type
print(type(my_var))
my_var = "Now I'm a string" # Now my_var has become str type
print(type(my_var))Mutable and Immutable Types
Data types can be classified as mutable or immutable based on whether their values can be changed after creation.
Immutable (Mutable): Once created, their values cannot be changed. If you perform a modification on a variable, it actually creates a new object.
- Includes:
int,float,complex,str,tuple,frozenset,bool,bytes
pythona = "hello" a[0] = 'H' # This will raise TypeError error because strings are immutable a = "world" # This is not a modification, but rather lets a point to a new string object- Includes:
Mutable (Mutable): After creation, their values can be changed, without needing to create a new object.
- Includes:
list,dict,set,bytearray
pythonmy_list = [1, 2, 3] my_list[0] = 99 # Modify directly on the original list print(my_list) # Output: [99, 2, 3]- Includes:
Understanding the difference between mutable and immutable types is crucial for writing efficient and bug-free Python code.