LoginSignup
0
0

タプル(tuple)は、Pythonの基本的なデータ構造の1つで、複数の要素をグループ化するために使用されます。リストと似ていますが、タプルは変更不可能(イミュータブル)であるという重要な特徴があります。

タプルの作成

# 丸括弧を使用して作成
fruits = ('apple', 'banana', 'orange')
print(fruits)  # 出力: ('apple', 'banana', 'orange')

# カンマを使用して作成(丸括弧は省略可能)
coordinates = 3, 4
print(coordinates)  # 出力: (3, 4)

# 1要素のタプルを作成する場合は、最後にカンマが必要
single_item = ('solo',)
print(single_item)  # 出力: ('solo',)

タプルへのアクセス

fruits = ('apple', 'banana', 'orange')

# インデックスを使用して要素にアクセス
print(fruits[0])  # 出力: apple
print(fruits[-1])  # 出力: orange

# スライシングを使用して部分タプルを取得
print(fruits[1:])  # 出力: ('banana', 'orange')

タプルの特徴: イミュータブル(変更不可)

coordinates = (3, 4)
# coordinates[0] = 5  # これはエラーになります
# TypeError: 'tuple' object does not support item assignment

# タプル全体を新しいタプルで置き換えることは可能
coordinates = (5, 6)
print(coordinates)  # 出力: (5, 6)

タプルの展開(アンパッキング)

# 複数の変数に値を代入
x, y = (10, 20)
print(x)  # 出力: 10
print(y)  # 出力: 20

# 余った要素を別のタプルに格納
first, *rest = (1, 2, 3, 4, 5)
print(first)  # 出力: 1
print(rest)   # 出力: [2, 3, 4, 5]

タプルの使用例

# 関数から複数の値を返す
def get_dimensions():
    return (1920, 1080)

width, height = get_dimensions()
print(f"Width: {width}, Height: {height}")
# 出力: Width: 1920, Height: 1080

# 辞書のキーとしてタプルを使用
locations = {
    (35.6895, 139.6917): "Tokyo",
    (40.7128, -74.0060): "New York"
}
print(locations[(35.6895, 139.6917)])  # 出力: Tokyo

タプルの利点

  • イミュータブルなので、データの整合性を保つのに役立ちます
  • リストよりも少しだけ高速です(特に大きなデータの場合)
  • 辞書のキーとして使用できます(リストは使用できません)
  • コードの意図を明確にします(データが変更されないことを示す)
# タプルを使って関数の戻り値の意図を明確にする
def get_user_info():
    return ("Alice", 30, "alice@example.com")

name, age, email = get_user_info()
print(f"Name: {name}, Age: {age}, Email: {email}")
# 出力: Name: Alice, Age: 30, Email: alice@example.com

タプルとリストの変換

# リストをタプルに変換
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # 出力: (1, 2, 3)

# タプルをリストに変換
back_to_list = list(my_tuple)
print(back_to_list)  # 出力: [1, 2, 3]

タプルは、変更されるべきでないデータの集合を表現するのに適しています。例えば、座標、RGB色値、ユーザーの基本情報など、一度設定されたら変更されないデータを扱う際に便利です。

参考) 東京工業大学情報理工学院 Python早見表

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