はじめに
この実験では、Python で変数がリスト (list) かどうかを確認する方法を学びます。これには、順序付けられた可変のアイテムのコレクションであるリストの基本的なデータ構造を理解することが含まれます。
この実験では、LabEx 環境の VS Code を使用して、数値のリスト、文字列のリスト、および混合データ型のリストなど、さまざまなタイプのリストを作成する方法を案内します。その後、インデックスを使用してリスト内の要素にアクセスする方法を探索します。さらに、type() や isinstance() などの Python の組み込み関数を使用してリストを識別する方法を実証します。
リストを理解する
このステップでは、Python で最も汎用性が高く基本的なデータ構造の 1 つであるリスト (list) について学びます。リストは、任意のデータ型のアイテムのコレクションを格納するために使用されます。リストは順序付けられており、つまりアイテムには特定の順序があり、可変であるため、作成後にその内容を変更することができます。
まずは簡単なリストを作成してみましょう。
LabEx 環境で VS Code エディタを開きます。
~/projectディレクトリにlists_example.pyという名前の新しいファイルを作成します。~/project/lists_example.pyファイルに以下のコードを追加します。
## Creating a list of numbers numbers = [1, 2, 3, 4, 5] print("List of numbers:", numbers) ## Creating a list of strings fruits = ["apple", "banana", "cherry"] print("List of fruits:", fruits) ## Creating a list of mixed data types mixed_list = [1, "hello", 3.14, True] print("List of mixed data types:", mixed_list)ここでは、整数を含む
numbers、文字列を含むfruits、およびデータ型の混合を含むmixed_listという 3 つの異なるリストを作成しました。ターミナルで以下のコマンドを使用してスクリプトを実行します。
python ~/project/lists_example.py以下の出力が表示されるはずです。
List of numbers: [1, 2, 3, 4, 5] List of fruits: ['apple', 'banana', 'cherry'] List of mixed data types: [1, 'hello', 3.14, True]
では、いくつかの一般的なリスト操作を探索してみましょう。
要素へのアクセス: インデックス (位置) を使用してリスト内の要素にアクセスすることができます。インデックスは最初の要素から 0 で始まります。
lists_example.pyに以下のコードを追加します。fruits = ["apple", "banana", "cherry"] print("First fruit:", fruits[0]) ## Accessing the first element print("Second fruit:", fruits[1]) ## Accessing the second element print("Third fruit:", fruits[2]) ## Accessing the third elementスクリプトを再度実行します。
python ~/project/lists_example.py以下の出力が表示されるはずです。
First fruit: apple Second fruit: banana Third fruit: cherry要素の変更: インデックスに新しい値を割り当てることで、リスト内の要素の値を変更することができます。
lists_example.pyに以下のコードを追加します。fruits = ["apple", "banana", "cherry"] fruits[1] = "grape" ## Changing the second element print("Modified list of fruits:", fruits)スクリプトを再度実行します。
python ~/project/lists_example.py以下の出力が表示されるはずです。
Modified list of fruits: ['apple', 'grape', 'cherry']要素の追加:
append()メソッドを使用して、リストの末尾に要素を追加することができます。lists_example.pyに以下のコードを追加します。fruits = ["apple", "banana", "cherry"] fruits.append("orange") ## Adding an element to the end print("List with added fruit:", fruits)スクリプトを再度実行します。
python ~/project/lists_example.py以下の出力が表示されるはずです。
List with added fruit: ['apple', 'banana', 'cherry', 'orange']
リストを理解し、それを操作する方法を習得することは、効果的な Python プログラムを書くために重要です。
type() を使って識別する
このステップでは、Python の type() 関数を使って変数のデータ型を識別する方法を学びます。データ型を理解することは、正しく効率的なコードを書くために重要です。type() 関数はオブジェクトの型を返します。
type() 関数を探索するために、新しい Python ファイルを作成しましょう。
LabEx 環境で VS Code エディタを開きます。
~/projectディレクトリにtype_example.pyという名前の新しいファイルを作成します。~/project/type_example.pyファイルに以下のコードを追加します。
## Using type() to identify data types number = 10 print("Type of number:", type(number)) floating_point = 3.14 print("Type of floating_point:", type(floating_point)) text = "Hello, LabEx!" print("Type of text:", type(text)) is_true = True print("Type of is_true:", type(is_true)) my_list = [1, 2, 3] print("Type of my_list:", type(my_list)) my_tuple = (1, 2, 3) print("Type of my_tuple:", type(my_tuple)) my_dict = {"name": "Alice", "age": 30} print("Type of my_dict:", type(my_dict))このコードでは、
type()を使って整数、浮動小数点数、文字列、ブール値、リスト、タプル、辞書など、さまざまな変数のデータ型を判定しています。ターミナルで以下のコマンドを使ってスクリプトを実行します。
python ~/project/type_example.py以下の出力が表示されるはずです。
Type of number: <class 'int'> Type of floating_point: <class 'float'> Type of text: <class 'str'> Type of is_true: <class 'bool'> Type of my_list: <class 'list'> Type of my_tuple: <class 'tuple'> Type of my_dict: <class 'dict'>
出力は各変数のデータ型を示しています。たとえば、<class 'int'> は変数が整数であることを示し、<class 'str'> は文字列であることを示します。
変数のデータ型を理解することは、正しく演算を行うために不可欠です。たとえば、文字列を整数に変換しないまま、文字列と整数を直接足すことはできません。type() 関数は、コード内のこれらの潜在的な問題を識別するのに役立ちます。
isinstance() で確認する
このステップでは、Python の isinstance() 関数を使って、オブジェクトが特定のクラスまたは型のインスタンスであるかどうかを確認する方法を学びます。これは、特に継承を扱う場合に、直接 type() を使うよりも堅牢なデータ型のチェック方法です。
isinstance() 関数を調べるために、新しい Python ファイルを作成しましょう。
LabEx 環境で VS Code エディタを開きます。
~/projectディレクトリにisinstance_example.pyという名前の新しいファイルを作成します。~/project/isinstance_example.pyファイルに以下のコードを追加します。
## Using isinstance() to confirm data types number = 10 print("Is number an integer?", isinstance(number, int)) floating_point = 3.14 print("Is floating_point a float?", isinstance(floating_point, float)) text = "Hello, LabEx!" print("Is text a string?", isinstance(text, str)) is_true = True print("Is is_true a boolean?", isinstance(is_true, bool)) my_list = [1, 2, 3] print("Is my_list a list?", isinstance(my_list, list)) my_tuple = (1, 2, 3) print("Is my_tuple a tuple?", isinstance(my_tuple, tuple)) my_dict = {"name": "Alice", "age": 30} print("Is my_dict a dictionary?", isinstance(my_dict, dict))このコードでは、
isinstance()を使って各変数が期待されるデータ型のインスタンスであるかどうかをチェックしています。isinstance()関数は、オブジェクトが指定された型のインスタンスであればTrueを返し、そうでなければFalseを返します。ターミナルで以下のコマンドを使ってスクリプトを実行します。
python ~/project/isinstance_example.py以下の出力が表示されるはずです。
Is number an integer? True Is floating_point a float? True Is text a string? True Is is_true a boolean? True Is my_list a list? True Is my_tuple a tuple? True Is my_dict a dictionary? True
では、継承のシナリオを考えてみましょう。
isinstance_example.pyに以下のコードを追加します。class Animal: pass class Dog(Animal): pass animal = Animal() dog = Dog() print("Is animal an Animal?", isinstance(animal, Animal)) print("Is dog a Dog?", isinstance(dog, Dog)) print("Is dog an Animal?", isinstance(dog, Animal)) print("Is animal a Dog?", isinstance(animal, Dog))スクリプトを再度実行します。
python ~/project/isinstance_example.py以下の出力が表示されるはずです。
Is animal an Animal? True Is dog a Dog? True Is dog an Animal? True Is animal a Dog? Falseご覧のとおり、
isinstance()はDogがAnimalから継承しているため、DogもAnimalであると正しく識別します。これが、isinstance()がtype()で直接型を比較するよりも強力な点です。
isinstance() を使うことで、さまざまなデータ型や継承を扱う際に、コードがより柔軟で堅牢になります。
まとめ
この実験では、Python の基本的なデータ構造であるリストについて学びました。リストは、さまざまなデータ型の項目を順序付けて格納する可変のコレクションとして使用されます。数値、文字列、および混合データ型を含むリストを作成し、コンソールに出力しました。
また、この実験では、最初の要素を 0 とするインデックスを使用してリストの要素にアクセスする方法も紹介しました。果物のリストから特定の要素にアクセスして出力することで、この概念を実証しました。



