赋值运算符 #

赋值运算符用于给变量赋值。

一、基本赋值运算符 #

1.1 简单赋值 #

python
# 基本赋值
x = 10
name = "Tom"
items = [1, 2, 3]

# 赋值表达式返回值(Python 3.8+ 海象运算符)
if (n := len(items)) > 0:
    print(f"列表有{n}个元素")

1.2 链式赋值 #

python
# 多个变量赋同一值
a = b = c = 0
print(a, b, c)  # 0 0 0

# 注意:引用同一对象
a = b = []
a.append(1)
print(b)  # [1](b也被修改了)

# 安全的方式
a = []
b = []

二、复合赋值运算符 #

复合赋值运算符是算术运算符和赋值运算符的组合。

2.1 运算符列表 #

运算符 示例 等价于
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
//= x //= y x = x // y
%= x %= y x = x % y
**= x **= y x = x ** y
&= x &= y x = x & y
|= x |= y x = x | y
^= x ^= y x = x ^ y
<<= x <<= y x = x << y
>>= x >>= y x = x >> y

2.2 算术复合赋值 #

python
# 加法赋值
x = 10
x += 5
print(x)  # 15

# 减法赋值
x = 10
x -= 3
print(x)  # 7

# 乘法赋值
x = 10
x *= 2
print(x)  # 20

# 除法赋值
x = 10
x /= 4
print(x)  # 2.5(结果为浮点数)

# 整除赋值
x = 10
x //= 3
print(x)  # 3

# 取余赋值
x = 10
x %= 3
print(x)  # 1

# 幂赋值
x = 2
x **= 10
print(x)  # 1024

2.3 位运算复合赋值 #

python
# 按位与赋值
x = 15  # 1111
x &= 7  # 0111
print(x)  # 7

# 按位或赋值
x = 5   # 0101
x |= 2  # 0010
print(x)  # 7

# 按位异或赋值
x = 5   # 0101
x ^= 3  # 0011
print(x)  # 6

# 左移赋值
x = 5
x <<= 2
print(x)  # 20

# 右移赋值
x = 20
x >>= 2
print(x)  # 5

三、序列类型的复合赋值 #

3.1 字符串 #

python
# 字符串拼接
s = "Hello"
s += " World"
print(s)  # "Hello World"

# 字符串重复
s = "Ha"
s *= 3
print(s)  # "HaHaHa"

3.2 列表 #

python
# 列表拼接
items = [1, 2]
items += [3, 4]
print(items)  # [1, 2, 3, 4]

# 列表重复
items = [1]
items *= 3
print(items)  # [1, 1, 1]

# 注意:+= 与 extend() 类似
items = [1, 2]
items.extend([3, 4])
print(items)  # [1, 2, 3, 4]

# 但 += 可以接受元组
items = [1, 2]
items += (3, 4)
print(items)  # [1, 2, 3, 4]

3.3 元组(不可变) #

python
# 元组拼接会创建新对象
t = (1, 2)
t += (3, 4)
print(t)  # (1, 2, 3, 4)

# 元组重复
t = (1,)
t *= 3
print(t)  # (1, 1, 1)

四、复合赋值的区别 #

4.1 可变类型 #

python
# 列表:+= 在原对象上修改
items = [1, 2]
original_id = id(items)
items += [3, 4]
print(id(items) == original_id)  # True(同一对象)

# 列表:= 创建新对象
items = [1, 2]
original_id = id(items)
items = items + [3, 4]
print(id(items) == original_id)  # False(新对象)

4.2 不可变类型 #

python
# 字符串:+= 创建新对象
s = "Hello"
original_id = id(s)
s += " World"
print(id(s) == original_id)  # False

# 元组:+= 创建新对象
t = (1, 2)
original_id = id(t)
t += (3, 4)
print(id(t) == original_id)  # False

4.3 实际影响 #

python
# 在函数中修改可变参数
def add_item(items):
    items += [1]  # 修改原列表

my_list = []
add_item(my_list)
print(my_list)  # [1]

# 使用 = 创建新对象
def add_item_new(items):
    items = items + [1]  # 创建新列表

my_list = []
add_item_new(my_list)
print(my_list)  # [](未改变)

五、多重赋值 #

5.1 同时赋值多个变量 #

python
# 多变量赋值
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# 交换变量
x, y = 1, 2
x, y = y, x
print(x, y)  # 2 1

5.2 解包赋值 #

python
# 列表解包
items = [1, 2, 3]
a, b, c = items
print(a, b, c)  # 1 2 3

# 元组解包
point = (10, 20)
x, y = point
print(x, y)  # 10 20

# 字典解包
person = {"name": "Tom", "age": 25}
key1, key2 = person  # 解包键
print(key1, key2)  # name age

5.3 星号表达式 #

python
# 扩展解包(Python 3+)
first, *rest = [1, 2, 3, 4, 5]
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

*beginning, last = [1, 2, 3, 4, 5]
print(beginning)  # [1, 2, 3, 4]
print(last)       # 5

first, *middle, last = [1, 2, 3, 4, 5]
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

六、海象运算符 (:=) #

Python 3.8+ 引入的海象运算符,允许在表达式中赋值。

6.1 基本用法 #

python
# 在条件中使用
if (n := len([1, 2, 3, 4, 5])) > 3:
    print(f"列表长度{n},大于3")

# 在while循环中使用
lines = ["line1", "line2", ""]
i = 0
while (line := lines[i]) != "":
    print(line)
    i += 1

6.2 减少重复计算 #

python
# 传统写法
text = "Hello World"
match = None
if len(text) > 10:
    match = text[:10]
print(match)

# 使用海象运算符
if (match := text[:10]) and len(match) > 5:
    print(match)

6.3 在列表推导式中 #

python
# 计算并过滤
data = [1, -2, 3, -4, 5]
results = [y for x in data if (y := x * 2) > 0]
print(results)  # [2, 6, 10]

七、赋值与可变性 #

7.1 可变类型 #

python
# 列表
a = [1, 2, 3]
b = a
a += [4]      # 修改原列表
print(b)      # [1, 2, 3, 4](b也被修改)

# 字典
d1 = {"a": 1}
d2 = d1
d1["b"] = 2
print(d2)     # {'a': 1, 'b': 2}

7.2 不可变类型 #

python
# 字符串
s1 = "Hello"
s2 = s1
s1 += " World"  # 创建新字符串
print(s2)       # "Hello"(s2不变)

# 元组
t1 = (1, 2)
t2 = t1
t1 += (3,)      # 创建新元组
print(t2)       # (1, 2)(t2不变)

7.3 使用copy避免引用问题 #

python
import copy

# 浅拷贝
a = [1, 2, [3, 4]]
b = a.copy()
a[0] = 10
print(b[0])  # 1(不变)
a[2][0] = 30
print(b[2])  # [30, 4](变了!)

# 深拷贝
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
a[2][0] = 30
print(b[2])  # [3, 4](不变)

八、常见陷阱 #

8.1 可变默认参数 #

python
# 错误示例
def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2](意外!)

# 正确做法
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

8.2 类属性共享 #

python
class MyClass:
    items = []  # 类属性,所有实例共享

a = MyClass()
b = MyClass()
a.items.append(1)
print(b.items)  # [1](共享了)

# 正确做法
class MyClass:
    def __init__(self):
        self.items = []  # 实例属性

8.3 += 与 = + #

python
# 对可变类型,+= 修改原对象
items = [1, 2]
items_id = id(items)
items += [3]
print(id(items) == items_id)  # True

# = + 创建新对象
items = [1, 2]
items_id = id(items)
items = items + [3]
print(id(items) == items_id)  # False

九、总结 #

运算符 名称 示例
= 赋值 x = 5
+= 加法赋值 x += 3
-= 减法赋值 x -= 3
*= 乘法赋值 x *= 2
/= 除法赋值 x /= 2
//= 整除赋值 x //= 2
%= 取余赋值 x %= 3
**= 幂赋值 x **= 2
:= 海象运算符 if (x := 5) > 0:

要点:

  • 可变类型使用 += 会修改原对象
  • 不可变类型使用任何赋值都会创建新对象
  • 注意可变默认参数陷阱
  • 海象运算符可在表达式中赋值(Python 3.8+)
最后更新:2026-03-16