はじめに
この実験(Lab)では、Python におけるタプル(tuple)について包括的に理解を深めます。タプルの作成方法、インデックス指定やスライスを使用した要素へのアクセス方法、そしてそのイミュータブル(immutable:不変)な性質について学習します。また、タプル演算子、アンパッキング、および一般的な組み込み関数を使用して、タプルデータを効率的に操作する練習を行います。
タプルの作成とアクセス
このステップでは、タプルの作成方法と要素へのアクセス方法を学習します。タプルは順序付けられたイミュータブル(immutable:不変)なアイテムのコレクションであり、一度作成されるとその内容を変更することはできません。
まず、WebIDE の左側にあるファイルエクスプローラーを見つけます。tuple_basics.pyという名前のファイルを見つけて開いてください。このファイルにコードを記述していきます。
いくつかの異なる種類のタプルを作成することから始めましょう。以下のコードをtuple_basics.pyに追加してください。
## Create an empty tuple
empty_tuple = ()
print("Empty tuple:", empty_tuple)
print("Type of empty_tuple:", type(empty_tuple))
## Create a tuple with a single element (note the trailing comma)
single_element_tuple = (50,)
print("\nSingle element tuple:", single_element_tuple)
print("Type of single_element_tuple:", type(single_element_tuple))
## Create a tuple with multiple elements
fruits = ("apple", "banana", "cherry")
print("\nFruits tuple:", fruits)
## Create a tuple from a list using the tuple() constructor
numbers_list = [1, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print("\nTuple from list:", numbers_tuple)
コードを追加した後、ファイルを保存します(ショートカットキーCtrl+Sを使用できます)。次に、WebIDE の下部にあるターミナルを開き、次のコマンドでスクリプトを実行します。
python tuple_basics.py
タプルの作成と型が確認できる、以下の出力が表示されるはずです。
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
次に、タプル内の要素にアクセスする方法を学びます。インデックス指定(0 から開始)を使用して単一の要素を取得したり、スライスを使用して要素のサブシーケンスを取得したりできます。
以下のコードをtuple_basics.pyファイルの末尾に追加してください。
## Define a sample tuple for accessing elements
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("\nOriginal tuple:", my_tuple)
## Access elements using indexing
print("First element (index 0):", my_tuple[0])
print("Last element (index -1):", my_tuple[-1])
## Access elements using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])
print("Elements from index 2 to the end:", my_tuple[2:])
print("Reverse the tuple:", my_tuple[::-1])
再度ファイルを保存し、ターミナルからスクリプトを実行します。
python tuple_basics.py
完全な出力には、タプル要素へのアクセス結果が追加されます。
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
Original tuple: ('p', 'y', 't', 'h', 'o', 'n')
First element (index 0): p
Last element (index -1): n
Elements from index 1 to 3: ('y', 't', 'h')
Elements from index 2 to the end: ('t', 'h', 'o', 'n')
Reverse the tuple: ('n', 'o', 'h', 't', 'y', 'p')
これで、タプルを正常に作成し、その要素にアクセスすることができました。
タプルの不変性(Immutability)の理解
タプルの重要な特徴は、そのイミュータビリティ(不変性)です。これは、タプルが作成された後、その要素を変更したり、追加したり、削除したりできないことを意味します。このステップでは、タプルを変更しようとしたときに何が起こるかを確認し、新しいタプルを作成することによって「変更」を実現する正しい方法を学びます。
ファイルエクスプローラーからtuple_modification.pyファイルを開いてください。
まず、タプル内の要素を直接変更してみましょう。以下のコードをtuple_modification.pyに追加します。変更を試みる行はコメントアウトされています。
my_tuple = ('a', 'b', 'c', 'd', 'e')
print("Original tuple:", my_tuple)
## The following line will cause a TypeError because tuples are immutable.
## You can uncomment it to see the error for yourself.
## my_tuple[0] = 'f'
もし、最後から 2 番目の行のコメントアウトを解除してコードを実行した場合、Python は停止し、TypeError: 'tuple' object does not support item assignmentというエラーが表示されます。
タプルをインプレース(その場で)で変更できないため、解決策は目的の変更を加えた新しいタプルを作成することです。これは、スライスと連結(+)を使用して行うことができます。
要素を「置き換える」方法を確認するために、以下のコードをtuple_modification.pyの末尾に追加してください。
## "Modify" a tuple by creating a new one
## Concatenate a new single-element tuple ('f',) with a slice of the original tuple
modified_tuple = ('f',) + my_tuple[1:]
print("New 'modified' tuple:", modified_tuple)
print("Original tuple is unchanged:", my_tuple)
同様に、要素を除外した新しいタプルを作成することで、要素を「削除」することもできます。このコードをファイルに追加してください。
## "Delete" an element by creating a new tuple
## Concatenate the slice before the element with the slice after the element
tuple_after_deletion = my_tuple[:2] + my_tuple[3:] ## Excludes element at index 2 ('c')
print("\nNew tuple after 'deletion':", tuple_after_deletion)
ファイルを保存し、ターミナルから実行します。
python tuple_modification.py
出力は、元のタプルが変更されていないまま、新しいタプルが作成されたことを示します。
Original tuple: ('a', 'b', 'c', 'd', 'e')
New 'modified' tuple: ('f', 'b', 'c', 'd', 'e')
Original tuple is unchanged: ('a', 'b', 'c', 'd', 'e')
New tuple after 'deletion': ('a', 'b', 'd', 'e')
このステップは、タプルのイミュータブルな性質と、この制限を回避するための標準的な方法を強調しています。
タプル演算子とアンパッキングの使用
Python は、タプルを操作するためのいくつかの便利な演算子を提供します。また、タプルの要素を複数の変数に一度に割り当てることができる強力な機能であるタプルアンパッキングについても学習します。
ファイルエクスプローラーからtuple_operators.pyファイルを開いてください。
連結(+)、繰り返し(*)、メンバーシップ(in)演算子を探ってみましょう。以下のコードをtuple_operators.pyに追加してください。
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
## Concatenation (+)
concatenated_tuple = tuple1 + tuple2
print("Concatenated:", concatenated_tuple)
## Repetition (*)
repeated_tuple = tuple1 * 3
print("Repeated:", repeated_tuple)
## Membership (in)
is_present = 'b' in tuple2
print("\nIs 'b' in tuple2?", is_present)
is_absent = 5 in tuple1
print("Is 5 in tuple1?", is_absent)
ファイルを保存し、ターミナルから実行します。
python tuple_operators.py
これらの操作の結果が表示されます。
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
次に、タプルアンパッキングを探ってみましょう。これにより、タプルの要素を単一の読みやすい行で複数の変数に割り当てることができます。変数の数はタプルの要素の数と一致する必要があります。
以下のコードをtuple_operators.pyの末尾に追加してください。
## Tuple unpacking
person_info = ("Alice", 30, "Engineer")
name, age, profession = person_info
print("\nOriginal info tuple:", person_info)
print("Unpacked Name:", name)
print("Unpacked Age:", age)
print("Unpacked Profession:", profession)
再度ファイルを保存し、スクリプトを実行します。
python tuple_operators.py
出力には、アンパックされた変数の結果が含まれるようになります。
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
Original info tuple: ('Alice', 30, 'Engineer')
Unpacked Name: Alice
Unpacked Age: 30
Unpacked Profession: Engineer
タプルアンパッキングは、複数の値を返す関数(多くの場合タプルで返されます)を扱う際に特に便利です。
組み込み関数とメソッドの適用
この最終ステップでは、タプルに対して動作する一般的な組み込み関数とメソッドの使用方法を学びます。タプルには主にcount()とindex()の 2 つのメソッドがあり、多くの汎用関数と組み合わせて使用できます。
ファイルエクスプローラーからtuple_functions.pyファイルを開いてください。
まず、タプルメソッドから始めましょう。count()は要素が出現する回数を返し、index()は要素が最初に出現するインデックスを返します。
以下のコードをtuple_functions.pyに追加してください。
my_tuple = (1, 5, 2, 8, 5, 3, 5, 9)
print("Tuple:", my_tuple)
## count() method
count_of_5 = my_tuple.count(5)
print("Count of 5:", count_of_5)
## index() method
index_of_8 = my_tuple.index(8)
print("Index of 8:", index_of_8)
次に、len()、max()、min()、sum()、sorted()など、タプルで非常に役立つ組み込み関数をいくつか使用します。
以下のコードをtuple_functions.pyの末尾に追加してください。
number_tuple = (10, 5, 20, 15, 30, 5)
print("\nNumber tuple:", number_tuple)
## len() function
print("Length:", len(number_tuple))
## max() and min() functions
print("Maximum value:", max(number_tuple))
print("Minimum value:", min(number_tuple))
## sum() function (for numeric tuples)
print("Sum of elements:", sum(number_tuple))
## sorted() function (returns a new sorted list)
sorted_list = sorted(number_tuple)
print("Sorted list from tuple:", sorted_list)
sorted()関数はタプルではなく新しいリストを返すことに注意してください。ソートされたタプルが必要な場合は、tuple(sorted_list)を使用して結果をタプルに変換できます。
ファイルを保存し、ターミナルから実行します。
python tuple_functions.py
出力は次のようになるはずです。
Tuple: (1, 5, 2, 8, 5, 3, 5, 9)
Count of 5: 3
Index of 8: 3
Number tuple: (10, 5, 20, 15, 30, 5)
Length: 6
Maximum value: 30
Minimum value: 5
Sum of elements: 85
Sorted list from tuple: [5, 5, 10, 15, 20, 30]
これで、タプルを検査および分析するための重要なメソッドと関数を使用する方法を学習しました。
まとめ
この実験(Lab)では、Python のタプルを使用するための強固な基礎を築きました。様々な方法でタプルを作成する方法、およびインデックス指定とスライスを使用して要素にアクセスする方法を学びました。タプルのイミュータビリティ(不変性)という核となる概念を探求し、「変更」を行うために新しいタプルを作成する練習をしました。また、タプルデータを扱うための一般的なタプル演算子(+や*など)、タプルアンパッキングの利便性、組み込みメソッド(count()、index())や関数(len()、max()、sorted())の有用性についても習熟しました。



