| 分類 | 類型 | 可變性 | 範例 |
|---|---|---|---|
| 數字 | int | 不可變 | 10, -5, 0b101, 0xFF |
| float | 不可變 | 3.14, -0.5, 1e3, 2.5e-2 | |
| complex | 不可變 | 3+4j, 1j | |
| bool | 不可變 | True, False (int 子類) | |
| 字串 | str | 不可變 | 'hello', "world", """多行""" |
| 列表 | list | **可變** | [1, 'a', [2,3], {'k':'v'}] |
| 元組 | tuple | 不可變 | (1, 2, 3), (42,), tuple('abc') |
| 字典 | dict | **可變** | {'name':'Tom', 'age':25} |
| 集合 | set / frozenset | 可變 / 不可變 | {1,2,3}, frozenset([1,2]) |
z = 3 + 4j
print(z.real, z.imag) # 3.0 4.0
print(abs(z)) # 5.0 (模)
print(z.conjugate()) # (3-4j)
s1 = 'single quote'
s2 = "double quote"
s3 = '''triple single'''
s4 = """triple double"""
s = ' Hello World '
print(s.strip()) # 'Hello World'
print(s.lower(), s.upper())
print(s.split()) # ['Hello', 'World']
print(','.join(['a','b'])) # 'a,b'
print(s.replace('World', 'Python'))
print(f'Value: {42}') # f-string (3.6+)
print('{} {}'.format('a', 'b'))
lst = [1, 2, 3, 4, 5]
print(lst[0], lst[-1]) # 1, 5
print(lst[1:4]) # [2, 3, 4] (切片: 含頭不含尾)
print(lst[::2]) # [1, 3, 5] (步長 2)
print(lst[::-1]) # [5, 4, 3, 2, 1] (反轉)
lst.append(6) # [1,2,3,4,5,6]
lst.extend([7,8]) # [1,2,3,4,5,6,7,8]
lst.insert(0, 0) # [0,1,2,3,4,5,6,7,8]
lst.pop() # 移除並回傳最後一個
lst.pop(0) # 移除並回傳索引 0
lst.remove(3) # 移除第一個值為 3 的元素
lst[2:4] = ['a', 'b'] # 切片指派
del lst[0] # 刪除索引 0
lst.clear() # 清空
print(lst.count(2)) # 出現次數
print(lst.index(3)) # 第一次出現索引
lst.sort() # 就地排序
lst.reverse() # 就地反轉
sorted_lst = sorted(lst) # 回傳新列表
[x*2 for x in range(5)] # [0,2,4,6,8]
[x for x in range(10) if x%2==0] # [0,2,4,6,8]
[(x,y) for x in range(3) for y in range(2)]
d = {'name': 'Tom', 'age': 25}
print(d['name']) # 'Tom' (不存在拋 KeyError)
print(d.get('gender')) # None (不存在回傳預設)
print(d.get('gender', 'M')) # 'M'
d['email'] = 'tom@example.com' # 新增/更新
d.update({'city': 'Taipei', 'age': 26})
for k, v in d.items():
print(k, v)
# 字典生成式
{x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
s = {1, 2, 3, 3, 2} # {1, 2, 3} 自動去重
s.add(4)
s.discard(2) # 不存在不報錯
s.remove(1) # 不存在拋 KeyError
a = {1,2,3}
b = {3,4,5}
print(a | b) # 聯集 {1,2,3,4,5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1,2}
print(a ^ b) # 對稱差集 {1,2,4,5}
print(type(42)) #
print(isinstance(42, int)) # True
# 互轉
int('123') # 123
float('3.14') # 3.14
str(42) # '42'
list('abc') # ['a','b','c']
tuple([1,2]) # (1,2)
set([1,2,2,3]) # {1,2,3}
dict([('a',1),('b',2)]) # {'a':1,'b':2}
def modify_list(lst):
lst.append(99)
def modify_int(x):
x = 99
a = [1,2,3]
modify_list(a)
print(a) # [1,2,3,99] ← 原物件被修改
b = 10
modify_int(b)
print(b) # 10 ← 整數不可變,函數內重新綁定區域變數
**預設參數陷阱**:
def bad_append(x, lst=[]): # 危險!預設列表只建立一次
lst.append(x)
return lst
print(bad_append(1)) # [1]
print(bad_append(2)) # [1, 2] ← 共享同一列表!
def good_append(x, lst=None):
if lst is None: lst = []
lst.append(x)
return lst