読者です 読者をやめる 読者になる 読者になる

python タプルとリストの違い

<span class="synComment"># リストとタプルの違い</span>
a = [10, 20, 30] <span class="synComment"># リスト</span>
b = (10, 20, 30) <span class="synComment"># タプル</span>

<span class="synComment"># 中身が同じでも等しくないと判定される</span>
<span class="synStatement">assert</span> <span class="synStatement">not</span> a == b
<span class="synComment"># 型を合わせれば等しいと判定される</span>
<span class="synStatement">assert</span> tuple(a) == b
<span class="synStatement">assert</span> a == list(b)

<span class="synComment"># 要素へのアクセス方法は同じ</span>
<span class="synComment"># スライスも可能</span>
<span class="synStatement">assert</span> a[0] == 10
<span class="synStatement">assert</span> b[0] == 10
c = a[1:3]
d = b[1:3]
<span class="synComment"># スライスで返却されるのは元と同じ型</span>
<span class="synStatement">assert</span> c == [20, 30]
<span class="synStatement">assert</span> d == (20, 30)

<span class="synComment"># リストは変更可能だがタプルは変更不可能</span>
<span class="synStatement">try</span>:
    a[0] = 40
    b[0] = 40
<span class="synStatement">except</span> TypeError, e:
    <span class="synStatement">assert</span> e.message == "<span class="synConstant">'tuple' object does not support item assignment</span>"

<span class="synStatement">assert</span> a == [40, 20, 30]
a[0] = 10
<span class="synStatement">assert</span> a == [10, 20, 30]

<span class="synStatement">try</span>:
    a.append(40)
    b.append(40)
<span class="synStatement">except</span> AttributeError, e:
    <span class="synStatement">assert</span> e.message == "<span class="synConstant">'tuple' object has no attribute 'append'</span>"

<span class="synStatement">assert</span> a == [10, 20, 30, 40]
<span class="synStatement">assert</span> a.pop() == 40
<span class="synStatement">assert</span> a == [10, 20, 30]

<span class="synStatement">assert</span> len(a) == 3
<span class="synStatement">assert</span> len(b) == 3

<span class="synComment"># タプルはマップのキーにできる</span>
e = { (127, 0,0, 1): '<span class="synConstant">localhost</span>' }
<span class="synStatement">assert</span> e[(127, 0, 0, 1)] == '<span class="synConstant">localhost</span>'

<span class="synComment"># リストでは不可能</span>
<span class="synStatement">try</span>:
    f = { [127, 0,0, 1]: '<span class="synConstant">localhost</span>' }
<span class="synStatement">except</span> TypeError, e:
    <span class="synStatement">assert</span> e.message == '<span class="synConstant">list objects are unhashable</span>'