- 最終更新
- 2026/08/17
3秒でわかる
生成したあとで中身を書き換えられる性質のこと。Python のリストや辞書がこれにあたり、共有されると意図しない変更が伝わります。
30秒図解
もう少し詳しく
どういうものか
ミュータブルは、オブジェクトを作った
見分けるid です。
nums = [1, 2]
print(id(nums))
nums.append(3)
print(id(nums)) # 同じ id のまま中身だけ増える
s = "ab"
print(id(s))
s += "c"
print(id(s)) # 別の id。新しい文字列が作られているなぜ必要か
この
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4] a も増えている
c = a.copy() # 別の実体を作る
c.append(5)
print(a) # [1, 2, 3, 4] こちらは影響なし関数に渡した
具体例
もっとも
def add_item(item, cart=[]): # 危険
cart.append(item)
return cart
print(add_item("りんご")) # ['りんご']
print(add_item("みかん")) # ['りんご', 'みかん'] 前回の中身が残る
def add_item_safe(item, cart=None): # 正しい書き方
if cart is None:
cart = []
cart.append(item)
return cartデフォルト値は
つまずきやすいところ
タプルは
辞書の
似た用語との違い
| 分類 | Python の例 | 書き換え |
|---|---|---|
| ミュータブル | list, dict, set | 同じ実体のまま変わる |
| イミュータブル | int, str, tuple | 変えると |


