型の均一性を調べる
このステップでは、Python の型の均一性について学びます。型の均一性とは、リストや辞書などのコレクション内のすべての要素が同じデータ型であることを保証する概念を指します。これは、コードの一貫性を維持し、予期しないエラーを回避するために重要です。
まず、この概念を調べる Python スクリプトを作成しましょう。
-
LabEx 環境で VS Code エディタを開きます。
-
~/project
ディレクトリに type_uniformity.py
という名前の新しいファイルを作成します。
touch ~/project/type_uniformity.py
-
エディタで type_uniformity.py
ファイルを開きます。
では、type_uniformity.py
ファイルにいくつかのコードを追加して、同じ型の要素を持つリストを作成しましょう。
## Create a list of integers
int_list = [1, 2, 3, 4, 5]
## Print the list
print("List of integers:", int_list)
## Verify the type of each element
for item in int_list:
print("Type of", item, "is", type(item))
このコードでは、整数値のみを含む int_list
という名前のリストを作成します。その後、リストを反復処理し、type()
関数を使用して各要素の型を出力します。
次に、異なる型の要素を持つリストを作成しましょう。
## Create a list of mixed data types
mixed_list = [1, "hello", 3.14, True]
## Print the list
print("\nList of mixed data types:", mixed_list)
## Verify the type of each element
for item in mixed_list:
print("Type of", item, "is", type(item))
このコードでは、整数、文字列、浮動小数点数、ブール値を含む mixed_list
という名前のリストを作成します。その後、リストを反復処理し、各要素の型を出力します。
では、スクリプトを実行して出力を確認しましょう。
-
VS Code 環境でターミナルを開きます。
-
~/project
ディレクトリに移動します。
cd ~/project
-
python
コマンドを使用して type_uniformity.py
スクリプトを実行します。
python type_uniformity.py
以下のような出力が表示されるはずです。
List of integers: [1, 2, 3, 4, 5]
Type of 1 is <class 'int'>
Type of 2 is <class 'int'>
Type of 3 is <class 'int'>
Type of 4 is <class 'int'>
Type of 5 is <class 'int'>
List of mixed data types: [1, 'hello', 3.14, True]
Type of 1 is <class 'int'>
Type of hello is <class 'str'>
Type of 3.14 is <class 'float'>
Type of True is <class 'bool'>
ご覧のように、int_list
は同じ型 (int
) の要素を含み、mixed_list
は異なる型 (int
、str
、float
、bool
) の要素を含んでいます。
型の均一性を理解することは、堅牢で保守可能な Python コードを書くために重要です。次のステップでは、all()
関数と type()
関数を組み合わせて、コレクションの型の均一性をチェックする方法を学びます。