0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 3 エンジニア認定基礎試験 合格に向けて part3 (ミュータブル:イミュータブル)

Posted at

用語の整理

  • リスト (list)

    • 記号: []
    • ミュータブル(mutable):変更できる
    • 要素の追加 (append)、変更、削除 (remove, del) が可能。
  • タプル (tuple)

    • 記号: ()
    • イミュータブル(immutable):変更できない
    • 要素の追加・削除はできない。
  • 辞書 (dict)

    • 記号: {キー: 値}
    • ミュータブル(mutable):値を変更できる
    • キーは重複できない(後から同じキーを入れると上書きされる)。
  • 集合 (set)

    • 記号: {値, 値, ...} または set()
    • ミュータブル(mutable):要素の追加 (add)・削除 (remove) が可能
    • 同じ値は自動的に重複除去される(つまり、同じ値を2回入れても1つだけ残る)

確認用の例

# リスト(重複OK)
my_list = [1, 1, 2]
print(my_list)   # [1, 1, 2]  ← 重複がそのまま残る

# 集合(重複NG)
my_set = {1, 1, 2}
print(my_set)    # {1, 2}  ← 重複が自動的に消える

# 集合に要素を追加・削除
my_set.add(3)
print(my_set)    # {1, 2, 3}
my_set.remove(2)
print(my_set)    # {1, 3}

まとめ

  • mutable(ミュータブル):変更可能なオブジェクト(list, dict, set)
  • immutable(イミュータブル):変更不可能なオブジェクト(tuple, str, int など)
  • 集合(set)は重複を許さない

例題として次のように整理すると覚えやすいです:

data = {1, 2, 2, 3}
print(data)  # {1, 2, 3} ← 自動で重複削除

こういう性質があるので、集合は「重複を取り除きたいとき」に便利です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?