Python Data Types
中文版:Python 数据类型
Python’s built-in data types categorized by their purpose and mutability.
Overview
Python provides several built-in data types. Each type determines what kind of value a variable can hold and what operations can be performed on it. A key property is mutability: whether an object can be modified after creation.
Built-in Types Summary
| Data Type | Category | Description | Mutability |
|---|---|---|---|
int | Numeric | Integer number (e.g., 5, -3). | Immutable |
float | Numeric | Floating-point numbers (e.g., 3.14, -0.5). | Immutable |
complex | Numeric | Complex numbers (e.g., 3+4j). | Immutable |
str | Text | Sequence of Unicode characters (e.g., "hello"). | Immutable |
bool | Boolean | Boolean values: True or False. | Immutable |
list | Sequence | Ordered, mutable collection (e.g., [1, "a", True]). | Mutable |
tuple | Sequence | Ordered, immutable collection (e.g., (1, "a", True)). | Immutable |
range | Sequence | Immutable sequence of numbers (e.g., range(5)). | Immutable |
dict | Mapping | Unordered key-value pairs (e.g., {"name": "Alice"}). | Mutable |
set | Set | Unordered collection of unique elements (e.g., {1, 2, 3}). | Mutable |
NoneType | None | Represents the absence of a value (None). | Immutable |
Numeric Types
# Integer
age = 25
print(age) # Output: 25
# Float
price = 19.99
print(price) # Output: 19.99
# Complex
z = 3 + 4j
print(z.real) # Output: 3.0
print(z.imag) # Output: 4.0Boolean Type
is_empty = False
print(5 > 3) # Output: True
print(5 < 3) # Output: False
print(not is_empty) # Output: TrueText Type (String)
greeting = "Hello, Python!"
print(greeting[0:5]) # Output: Hello
print(len(greeting)) # Output: 13Sequence Types
List (Mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']Tuple (Immutable)
colors = ("red", "green", "blue")
print(colors[1]) # Output: green
# colors[1] = "yellow" # Error: tuples are immutableRange
numbers = list(range(1, 10, 2))
print(numbers) # Output: [1, 3, 5, 7, 9]
numbers = range(5) # start = 0; step = 1
print(list(numbers)) # Output: [0, 1, 2, 3, 4]Mapping Type (Dictionary)
person = {
"name": "Alice",
"age": 30,
"city": "Paris"
}
print(person["name"]) # Output: Alice
person["email"] = "alice@example.com" # Add new key-value pairSet Type
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # Output: {1, 2, 3} (duplicates removed)
unique_numbers.add(40)
print(unique_numbers) # Output: {1, 2, 3, 40}Warning
Sets are unordered collections. Accessing elements by index (e.g.,
my_set[0]) raises aTypeError.
NoneType
result = None
print(result) # Output: NoneType Checking and Conversion
a = 2
print(type(a)) # <class 'int'>
a = float(a) # 2.0
a = str(a) # '2'Related Concepts
- Python Variables — How variables hold values of these types
- Python Control Flow — Using collections in loops and conditions
- Introduction to Python — The lecture covering these topics