Basic Data Types
Python’s data types can be divided into basic data types and composite (container) data types, as well as some special data types. Below is a detailed classification and explanation:
1. Basic Data Types (Single Value)
- 1. Numeric Types (Number) Used to represent numbers, including the following subtypes: integers (int), floating-point numbers (float), and complex numbers
- 2. Strings (str) An immutable sequence of characters used to represent text information
- 3. Boolean Values (bool)
- 4. None Type (NoneType)
2. Composite Data Types (Containers that Store Multiple Values)
Lists (list) are mutable sequences, represented by square brackets []; elements can be of any data type and can be mixed, supporting addition, deletion, modification, and querying.
Tuples (tuple) are immutable sequences, represented by parentheses (); element types can be mixed, but cannot be modified after definition.
Dictionaries (dict) are collections of key-value pairs, represented by curly braces {}; keys (key) and values (value) correspond, with keys being unique and must be of an immutable type, while values can be of any type.
Sets (set) are collections of unordered, unique elements, represented by curly braces {} or set(); suitable for deduplication, intersection, union, and other operations.
3. Special Types
function: Function type
generator: Generator (a function with yield, such as (x for x in range(5)))
range: Range sequence (e.g., range(10), generates integers from 0 to 9)
slice: Slice object (e.g., 1:3 in list[1:3] corresponds to slice(1,3))
iterator: Iterators, mapping views (e.g., dict_keys), and other subtypes
4. Extended Types (Provided by Standard Library)
These types need to be imported from the standard library and are considered “commonly used extended types”:
Enum: Enumeration type, imported via the enum module
Types related to datetime
Regular expression match objects (re.Match)
In practical use, mastering basic types, container types, and function types can cover over 90% of scenarios. You can check the specific type of any variable using type(variable).
Details on Number:
Integers (int):
The most common part, which we understand as integer numbers, supports positive and negative values of any size (in Python 3, int can be of unlimited size). We will discuss why Python’s integers can support unlimited size.
Integers support all mathematical operations in mathematics: addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (Python uses two asterisks (**) to represent this).
print(2 + 3)
print(2 - 3)
print(2 * 3)
print(2 / 3)
print(2 ** 3)
Why Python integers (int) can be unlimited in size: Unlike static typed languages like C (where int is typically 4 bytes with a maximum value of (2^{31}-1 = 2147483647)), Python’s int uses a variable-length storage structure: it dynamically allocates memory based on the size of the integer. The larger the integer, the more memory it occupies; as long as the system memory is sufficient, it can represent integers of any size.
# Define a very large integer
big_num = 10**1000 # 1 followed by 1000 zeros (thousand-digit number)
print(big_num) # Outputs this huge number normally, no overflow
# Operations on large integers
result = big_num * 2 + 5
print(result) # Outputs 2000...005 (correct calculation, no overflow)
Floating-point Numbers (float):
Numbers with decimal parts, supporting scientific notation. Python’s floating-point numbers are not unlimited and do not use a variable-length storage structure—standard double-precision floating-point numbers (64 bits) have a fixed range and storage structure, which is completely different from the “variable-length unlimited” feature of integers. Python’s floating-point numbers (float type) directly map to C’s double type in CPython, using fixed 64-bit binary storage.
When dividing any two numbers, the result is always a floating-point number, even if both numbers are integers and can divide evenly:
print(6/3) # Outputs 2.0
In any other operation, if one operand is an integer and the other is a floating-point number, the result is also always a floating-point number:
print(1 + 1.0) # Outputs 2.0
Complex Numbers (complex): Composed of real and imaginary parts, which we use less frequently.
Strings (str)
An immutable sequence of characters used to represent text information, enclosed in single quotes ‘, double quotes “, or triple quotes ”’ or “””. Strings are both commonly used and extremely important; we will discuss strings in a separate article.
Boolean Type (bool)
Can only be True or False. Importantly, the boolean conversion relationship: In Python, all objects can be converted to a boolean value using the bool() function, following the rule that “empty/zero/None is False, non-empty/non-zero is True”.
Empty/zero/None being False is very important; it is key for future if statements checking for emptiness, providing a concise, efficient, and Pythonic method.Recommended Method
# Check if list is empty
list_empty = []
if not list_empty:
print("Empty List")
# Check if string is empty
str_empty = ""
if not str_empty:
print("Empty String")
Not Recommended Method
# Check if list is empty
list_empty = []
if list_empty == []:
print("Empty List")
# Check if string is empty
str_empty = ""
if str_empty == "":
print("Empty String")
Reasons Not Recommended
While it works, it has the following issues: 1. It couples specific types, which is not general enough and does not align with Python’s dynamic typing style; type changes can lead to failure. 2. It is redundant and not concise; Python’s “boolean context” has already defined the rule that “empty containers are False”; using if not obj directly aligns with Pythonic simplicity. 3. When implementing custom containers, you only need to correctly implement the __bool__ function to execute correctly in the emptiness logic.
None (None Type)
Used to represent a variable that “has not been assigned a value” or “the value does not exist”.There is only one None object in the entire Python program; all variables assigned to None point to the same instance (can be verified using id()).
data1 = None
data2 = None
print(hex(id(data1)))# Test output 0x7ffdf0441850
print(hex(id(data2)))# Test output 0x7ffdf0441850
Not equal to any value: None is not equal to 0, “” (empty string), [] (empty list), etc.; they are not equal in memory and are stored at different memory addresses.
In Python, if a function does not have an explicit return statement, it defaults to returning None.
To check if a None object is empty, use the following method:
None converted to bool is also False, but it cannot determine whether it is empty data or an uninitialized empty object. In the following situation, although the if condition is satisfied, it cannot determine if data points to the None object. If you want to know if data points to the None object, you can only use if data is None:
# Check if data is uninitialized
data = None
if data is None:
print("data is empty, data not initialized")
if not data:
print("data is empty, because None converted to bool is also False")
# Function defaults to returning None
def fun():
print("hello python")
result = fun()
print(result) # Outputs None
If you find this article somewhat helpful, please give it a thumbs up and a heart; it is the greatest encouragement for me. If it has helped you or if there are any inaccuracies in the content, please leave a comment to let me know. Thank you!