Python でリストが特定の長さを持っているかどうかを確認する方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python でリストが特定の長さを持っているかどうかを確認する方法を学びます。これには、リストの長さの概念を理解し、組み込みの len() 関数を利用してリスト内の要素の数を判断することが含まれます。

数値や文字列など、さまざまなデータ型を含むリストで len() 関数を使用する練習を行い、その結果を目的の長さと比較して、データを検証したり条件付きの操作を実行したりします。この実験では、Python の基本的なリスト操作技術を実践的に学ぶことができます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/lists("Lists") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559530{{"Python でリストが特定の長さを持っているかどうかを確認する方法"}} python/lists -.-> lab-559530{{"Python でリストが特定の長さを持っているかどうかを確認する方法"}} python/build_in_functions -.-> lab-559530{{"Python でリストが特定の長さを持っているかどうかを確認する方法"}} python/data_collections -.-> lab-559530{{"Python でリストが特定の長さを持っているかどうかを確認する方法"}} end

リストの長さについて学ぶ

このステップでは、Python におけるリストの長さの概念について学びます。リストの長さを判断する方法を理解することは、リストを繰り返し処理する、データを検証する、要素の数に基づいて計算を行うなど、多くのプログラミングタスクにとって基本的です。

リストの長さは、単にそれが含む要素の数です。Python では、任意のリストの長さを簡単に求めることができる組み込み関数 len() が用意されています。まずは簡単なリストを作成し、len() を使ってその長さを求めてみましょう。

まず、LabEx 環境で VS Code エディタを開きます。~/project ディレクトリに list_length.py という名前の新しいファイルを作成します。

## Create a list of numbers
numbers = [1, 2, 3, 4, 5]

## Use the len() function to find the length of the list
length = len(numbers)

## Print the length of the list
print(length)

ファイルを保存します。次に、ターミナルで python コマンドを使用して Python スクリプトを実行します。

python ~/project/list_length.py

以下の出力が表示されるはずです。

5

この出力は、リスト numbers が 5 つの要素を含んでいることを示しています。

次に、文字列のリストで試してみましょう。

## Create a list of strings
fruits = ["apple", "banana", "cherry"]

## Use the len() function to find the length of the list
length = len(fruits)

## Print the length of the list
print(length)

list_length.py の変更を保存し、再度スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

3

ご覧の通り、len() はさまざまなデータ型を含むリストでも機能します。

len() 関数の使用

前のステップでは、リストの長さの基本概念と len() 関数の使い方を学びました。このステップでは、len() 関数のさまざまな種類のリストやシナリオでの実用的な応用について探っていきます。

len() 関数は汎用性が高く、数値、文字列、さらには他のリストを含むさまざまなデータ型のリストで使用できます。これを説明するためにいくつかの例を見てみましょう。

~/project ディレクトリに作成した list_length.py ファイルを引き続き使用します。

まず、データ型が混在したリストを作成してみましょう。

## Create a list with mixed data types
mixed_list = [1, "hello", 3.14, True]

## Find the length of the mixed list
length = len(mixed_list)

## Print the length of the list
print(length)

list_length.py の変更を保存し、スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

4

これは、len() がデータ型に関係なく要素の数を正しくカウントすることを示しています。

次に、他のリストを含むリスト(ネストされたリスト)を試してみましょう。

## Create a nested list
nested_list = [[1, 2], [3, 4, 5], [6]]

## Find the length of the nested list
length = len(nested_list)

## Print the length of the list
print(length)

list_length.py の変更を保存し、再度スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

3

この場合、len()nested_list 内のサブリストの数をカウントします。サブリスト内の個々の要素はカウントされません。

最後に、空のリストを考えてみましょう。

## Create an empty list
empty_list = []

## Find the length of the empty list
length = len(empty_list)

## Print the length of the list
print(length)

list_length.py の変更を保存し、スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

0

空のリストの長さは 0 です。

これらの例は、Python でさまざまなリストのサイズを判断する際の len() 関数の柔軟性と有用性を示しています。

目標の長さと比較する

このステップでは、条件文を使ってリストの長さを目標の長さと比較する方法を学びます。これは、データを検証したり、リストのサイズに基づいて異なるアクションを実行したりする必要がある場合に、プログラミングで一般的に行われるタスクです。

len() 関数を if 文と組み合わせて、リストの長さが特定の値と一致するかどうかを確認します。

~/project ディレクトリで作業していた list_length.py ファイルを引き続き使用します。

まず、リストを作成し、その長さが目標の値と等しいかどうかを確認してみましょう。

## Create a list of names
names = ["Alice", "Bob", "Charlie"]

## Desired length
desired_length = 3

## Check if the length of the list is equal to the desired length
if len(names) == desired_length:
    print("The list has the desired length.")
else:
    print("The list does not have the desired length.")

list_length.py の変更を保存し、スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

The list has the desired length.

次に、リストを変更して、どうなるか見てみましょう。

## Create a list of names
names = ["Alice", "Bob"]

## Desired length
desired_length = 3

## Check if the length of the list is equal to the desired length
if len(names) == desired_length:
    print("The list has the desired length.")
else:
    print("The list does not have the desired length.")

list_length.py の変更を保存し、再度スクリプトを実行します。

python ~/project/list_length.py

今度は出力が以下のようになるはずです。

The list does not have the desired length.

また、>(より大きい)、<(より小さい)、>=(以上)、<=(以下)などの他の比較演算子を使用して、リストの長さを目標の長さと比較することもできます。

例えば:

## Create a list of numbers
numbers = [1, 2, 3, 4]

## Minimum length required
min_length = 3

## Check if the length of the list is greater than or equal to the minimum length
if len(numbers) >= min_length:
    print("The list meets the minimum length requirement.")
else:
    print("The list does not meet the minimum length requirement.")

list_length.py の変更を保存し、スクリプトを実行します。

python ~/project/list_length.py

出力は以下のようになるはずです。

The list meets the minimum length requirement.

このステップでは、len() 関数を条件文と組み合わせて、リストの長さを目標の長さと比較する方法を示しました。これにより、リストのサイズに基づいて異なるアクションを実行することができます。

まとめ

この実験では、Python におけるリストの長さの概念と、len() 関数を使ってそれを求める方法を学びました。数値や文字列が含まれるリストの長さを求める Python スクリプトを作成し、len() 関数の汎用性を実証しました。

この実験では、~/project ディレクトリに list_length.py ファイルを作成し、Python コードを記述してリストを定義し、len() 関数を使ってその長さを計算しました。その後、ターミナルで python コマンドを使用してスクリプトを実行し、出力を検証しました。