AITC Wiki

Python Data Types

Python 数据类型

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 TypeCategoryDescriptionMutability
intNumericInteger number (e.g., 5, -3).Immutable
floatNumericFloating-point numbers (e.g., 3.14, -0.5).Immutable
complexNumericComplex numbers (e.g., 3+4j).Immutable
strTextSequence of Unicode characters (e.g., "hello").Immutable
boolBooleanBoolean values: True or False.Immutable
listSequenceOrdered, mutable collection (e.g., [1, "a", True]).Mutable
tupleSequenceOrdered, immutable collection (e.g., (1, "a", True)).Immutable
rangeSequenceImmutable sequence of numbers (e.g., range(5)).Immutable
dictMappingUnordered key-value pairs (e.g., {"name": "Alice"}).Mutable
setSetUnordered collection of unique elements (e.g., {1, 2, 3}).Mutable
NoneTypeNoneRepresents 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.0

Boolean Type

is_empty = False
print(5 > 3)       # Output: True
print(5 < 3)       # Output: False
print(not is_empty)  # Output: True

Text Type (String)

greeting = "Hello, Python!"
print(greeting[0:5])  # Output: Hello
print(len(greeting))  # Output: 13

Sequence 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 immutable

Range

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 pair

Set 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 a TypeError.

NoneType

result = None
print(result)  # Output: None

Type Checking and Conversion

a = 2
print(type(a))   # <class 'int'>
a = float(a)     # 2.0
a = str(a)       # '2'

Sources