Python 数据类型与数据结构

Python 的内置数据类型与常用数据结构。

#type / concept #status / growing #resource / python #tech / lang / python

[!info] related notes

Python 数据类型与数据结构

Python 是动态类型语言,变量无需声明类型,类型在运行时确定。

核心机制

内置数据类型

类别类型示例
数值int, float, complex42, 3.14, 1+2j
文本str"hello"
布尔boolTrue, False
序列list, tuple, range[1,2,3], (1,2,3), range(5)
映射dict{"key": "value"}
集合set, frozenset{1,2,3}, frozenset({1,2})
二进制bytes, bytearray, memoryviewb"hello"
空值NoneNone

可变与不可变

  • 不可变: int, float, str, bool, tuple, frozenset, bytes
  • 可变: list, dict, set, bytearray, memoryview

类型检查

# 类型检查
type(42)           # <class 'int'>
isinstance(42, int)  # True

# 类型转换
int("42")          # 42
str(42)            # "42"
list("abc")        # ['a', 'b', 'c']

常见误解或边界

  1. 整数溢出: Python 整数无固定大小限制,会自动扩展
  2. 浮点精度: 0.1 + 0.2 != 0.3,需用 decimal 模块处理精确计算
  3. 字符串不可变: 修改字符串会创建新对象
  4. 列表 vs 元组: 列表可变,元组不可变;元组可作字典键,列表不行
创建于 2026/3/24 更新于 2026/5/27