LoginSignup
0
0

Pythonのlistとtupleの違い

Posted at

listとtupleの違いまとめ

  • listは可変なデータ型で、値の操作が自由にできる。
  • tupleは不変なデータ型で、値の操作ができない。
  • tupleはlistよりもメモリ使用量や処理速度が優れている。
  • listとtupleは、それぞれ適切な場面で使い分けることが重要である。

listのコード例

# listの作成
my_list = [1, 2, 3, "apple", "banana"]

# listの要素にアクセス
print(my_list[0]) # 1
print(my_list[-1]) # banana

# listの要素を変更
my_list[3] = "orange"
print(my_list) # [1, 2, 3, 'orange', 'banana']

# listに要素を追加
my_list.append(4)
print(my_list) # [1, 2, 3, 'orange', 'banana', 4]

# listから要素を削除
my_list.pop()
print(my_list) # [1, 2, 3, 'orange', 'banana']

tupleのコード例

# tupleの作成
my_tuple = (1, 2, 3, "apple", "banana")

# tupleの要素にアクセス
print(my_tuple[0]) # 1
print(my_tuple[-1]) # banana

# tupleの要素を変更(エラー)
my_tuple[3] = "orange" # TypeError: 'tuple' object does not support item assignment

# tupleに要素を追加(エラー)
my_tuple.append(4) # AttributeError: 'tuple' object has no attribute 'append'

# tupleから要素を削除(エラー)
my_tuple.pop() # AttributeError: 'tuple' object has no attribute 'pop'

簡単なスクリプト、登録・削除が必要な機能はlist、
変更予定はないが、ある程度まとまった数の値を管理する場合はtupleみたいなイメージで使い分けるとよいかも

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