回答編集履歴

1

説明追加

2021/03/09 14:38

投稿

ppaul
ppaul

スコア24666

test CHANGED
@@ -47,3 +47,51 @@
47
47
 
48
48
 
49
49
  空リストを要素とするタプルは、([],)と書きます。
50
+
51
+
52
+
53
+ ([],)はタプルなのでイミュータブルですが、その要素の[]はミュータブルです。
54
+
55
+ ```python
56
+
57
+ >>> x =([],)
58
+
59
+ >>> print(x)
60
+
61
+ ([],)
62
+
63
+ >>> x[0].append(42)
64
+
65
+ >>> print(x)
66
+
67
+ ([42],)
68
+
69
+ ```
70
+
71
+ このようなオブジェクトをunhashableあるいはhashableでないといいます。
72
+
73
+
74
+
75
+ unhashableなオブジェクトはdictのキーやsetの要素になることができません。
76
+
77
+
78
+
79
+ ```python
80
+
81
+ >>> d = {x:1}
82
+
83
+ Traceback (most recent call last):
84
+
85
+ File "<stdin>", line 1, in <module>
86
+
87
+ TypeError: unhashable type: 'list'
88
+
89
+ >>> s = set(x)
90
+
91
+ Traceback (most recent call last):
92
+
93
+ File "<stdin>", line 1, in <module>
94
+
95
+ TypeError: unhashable type: 'list'
96
+
97
+ ```