Python プログラム練習問題 10 選:リストを活用しよう!【初心者向け】
Python は、そのシンプルさと汎用性から、プログラミング初心者から経験豊富なエンジニアまで幅広く利用されています。特に、Python の強力な機能の一つである「リスト」は、様々な問題を解決するためのキーとなるデータ構造です。
この記事では、Python 初心者の方を対象に、リストを活用した練習問題 10 選を用意しました。各問題には、問題文、ヒント、解答例、そして解説を記載しています。これらの問題を通して、リストの基本的な操作から応用までを習得し、Python プログラミングのスキルアップを目指しましょう。
リストとは?
まず、リストについて簡単に説明します。リストは、複数の要素を順番に格納できるデータ構造です。要素は、数値、文字列、他のリストなど、様々な型のデータを取り込むことができます。リストは可変(mutable)なので、作成後に要素の追加、削除、変更が可能です。
リストの定義方法:
# 空のリスト my_list = [] # 数値のリスト numbers = [1, 2, 3, 4, 5] # 文字列のリスト fruits = ["apple", "banana", "orange"] # 異なる型の要素を含むリスト mixed_list = [1, "hello", True, [2, 3]]
Explanation: A list is a versatile data structure in Python used to store an ordered collection of items. These items can be of various data types like numbers, strings, booleans, or even other lists. Lists are mutable, meaning you can modify them after creation by adding, removing, or changing elements. The examples above demonstrate how to create empty lists, lists containing numbers, strings, and mixed data types.
基本的な操作:
- 要素へのアクセス:
my_list[index](インデックスは 0 から始まる) - 要素の追加:
my_list.append(element)、my_list.insert(index, element) - 要素の削除:
my_list.remove(element)、del my_list[index] - リストの長さ:
len(my_list)
Explanation: These are the fundamental operations you'll perform on lists:
- Accessing Elements: You access elements in a list using their index, which starts at 0. For example,
my_list[0]retrieves the first element. - Adding Elements:
append(element)adds an item to the end of the list.insert(index, element)inserts an item at a specific index in the list.
- Removing Elements:
remove(element)removes the first occurrence of a specified value from the list.del my_list[index]deletes the element at a given index.
- List Length:
len(my_list)returns the number of elements in the list.
練習問題 10 選
それでは、リストを活用した練習問題 10 選に取り組みましょう。
問題 1: リストの作成と要素へのアクセス
問題文: numbers = [10, 20, 30, 40, 50] というリストを作成し、3 番目の要素(インデックスは 2)の値を出力してください。
ヒント: my_list[index] でリストの要素にアクセスできます。
解答例:
numbers = [10, 20, 30, 40, 50] print(numbers[2]) # 出力: 30
解説: リスト numbers を定義し、インデックス 2 の要素にアクセスして出力しています。Python のリストのインデックスは 0 から始まることに注意してください。
Explanation: This problem tests your understanding of list creation and element access. Remember that Python lists are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. The code creates a list called numbers and then prints the value at index 2 (which is the third element).
問題 2: 要素の追加と削除
問題文: fruits = ["apple", "banana"] というリストを作成し、"orange" をリストの末尾に追加した後、"banana" をリストから削除して出力してください。
ヒント: append() で要素を末尾に追加、remove() で指定した値を削除できます。
解答例:
fruits = ["apple", "banana"] fruits.append("orange") fruits.remove("banana") print(fruits) # 出力: ['apple', 'orange']
解説: append() メソッドで "orange" をリストの末尾に追加し、remove() メソッドで "banana" をリストから削除しています。
Explanation: This problem focuses on modifying lists. You first add an element to the end of the list using append(). Then, you remove a specific value from the list using remove(). The output shows that "banana" has been successfully removed.
問題 3: リストの長さとループ処理
問題文: colors = ["red", "green", "blue"] というリストを作成し、リストの長さを出力した後、リスト内の各要素を順番に出力してください。
ヒント: len() でリストの長さを取得、for ループでリストの要素を反復処理できます。
解答例:
colors = ["red", "green", "blue"] print(len(colors)) # 出力: 3 for color in colors: print(color)
解説: len() 関数でリストの長さを取得し、for ループを使ってリスト内の各要素を順番に処理しています。
Explanation: This problem introduces you to working with the length of a list and iterating through its elements. len(colors) gives you the number of items in the list. The for color in colors: loop iterates over each element in the list, assigning it to the variable color for each iteration.
問題 4: リストのスライス
問題文: numbers = [1, 2, 3, 4, 5, 6] というリストから、インデックス 2 から 4 までの要素(3, 4, 5)をスライスで取り出し、出力してください。
ヒント: my_list[start:end] でリストのスライスを取得できます (end は含まれない)。
解答例:
numbers = [1, 2, 3, 4, 5, 6] sliced_list = numbers[2:5] print(sliced_list) # 出力: [3, 4, 5]
解説: numbers[2:5] でインデックス 2 (含む) から 5 (含まない) までの要素をスライスしています。
Explanation: Slicing allows you to extract a portion of a list. numbers[2:5] creates a new list containing elements from index 2 up to (but not including) index 5. This effectively extracts the sublist [3, 4, 5].
問題 5: リストのソート
問題文: random_numbers = [3, 1, 4, 1, 5, 9, 2, 6] というリストを昇順にソートして出力してください。
ヒント: sort() メソッドでリストをソートできます。
解答例:
random_numbers = [3, 1, 4, 1, 5, 9, 2, 6] random_numbers.sort() print(random_numbers) # 出力: [1, 1, 2, 3, 4, 5, 6, 9]
解説: sort() メソッドでリストを昇順にソートしています。sort() は元のリストを直接変更します。降順にソートする場合は、random_numbers.sort(reverse=True) とします。
Explanation: The sort() method arranges the elements of a list in ascending order by default. It modifies the original list directly. To sort in descending order, you can use the reverse=True argument: random_numbers.sort(reverse=True).
問題 6: リスト内包表記 (List Comprehension)
問題文: 0 から 9 までの数値のリストを作成し、各数値を2乗した新しいリストを作成してください。
ヒント: リスト内包表記を使うと、簡潔にリストを生成できます。
解答例:
squares = [x**2 for x in range(10)] print(squares) # 出力: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
解説: リスト内包表記 [x**2 for x in range(10)] は、range(10) で生成される各数値 x に対して x**2 (x の 2 乗) を計算し、その結果を新しいリストに格納します。
Explanation: List comprehensions provide a concise way to create new lists based on existing iterables. In this example, [x**2 for x in range(10)] iterates through the numbers from 0 to 9 (inclusive) using range(10), calculates the square of each number (x**2), and creates a new list containing these squares.
問題 7: リストのコピー
問題文: original_list = [1, 2, 3] というリストを作成し、このリストをコピーして new_list に代入してください。その後、original_list の要素を変更しても new_list が変更されないことを確認してください。
ヒント: copy() メソッドまたはスライスを使ってリストをコピーできます。
解答例:
original_list = [1, 2, 3] new_list = original_list.copy() # または new_list = original_list[:] original_list[0] = 100 print(original_list) # 出力: [100, 2, 3] print(new_list) # 出力: [1, 2, 3]
解説: copy() メソッドまたはスライスを使ってリストをコピーしています。これにより、original_list を変更しても new_list は元の値を保持します。単純に new_list = original_list とすると、new_list は original_list への参照となるため、一方を変更するともう一方も変更されます。
Explanation: It's crucial to understand the difference between creating a copy of a list and simply assigning one list to another variable. If you do new_list = original_list, both variables point to the same list in memory. Modifying original_list will also modify new_list. To create a true copy, use either the copy() method or slicing: new_list = original_list[:].
問題 8: リストの検索
問題文: names = ["Alice", "Bob", "Charlie", "David"] というリストから、"Charlie" のインデックスを検索してください。見つからない場合は -1 を出力してください。
ヒント: index() メソッドでリスト内の要素のインデックスを検索できます。
解答例:
names = ["Alice", "Bob", "Charlie", "David"] try: index = names.index("Charlie") print(index) # 出力: 2 except ValueError: print("-1")
解説: index() メソッドで "Charlie" のインデックスを検索しています。もし "Charlie" がリストに存在しない場合、ValueError 例外が発生するので、try-except ブロックを使って例外処理を行っています。
Explanation: The index() method searches for the first occurrence of a specified value in a list and returns its index. If the value is not found, it raises a ValueError. The try...except block handles this potential error gracefully by printing -1 if "Charlie" isn't in the list.
問題 9: リストの連結
問題文: list1 = [1, 2, 3] と list2 = [4, 5, 6] というリストを連結して新しいリストを作成し、出力してください。
ヒント: + 演算子でリストを連結できます。
解答例:
list1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = list1 + list2 print(combined_list) # 出力: [1, 2, 3, 4, 5, 6]
解説: + 演算子を使って list1 と list2 を連結し、新しいリスト combined_list に格納しています。
Explanation: The + operator concatenates two or more lists into a new list. This creates a new list containing all the elements from both original lists, without modifying them.
問題 10: リストの要素の合計
問題文: numbers = [1, 2, 3, 4, 5] というリスト内のすべての数値の合計を計算して出力してください。
ヒント: sum() 関数でリスト内の数値の合計を計算できます。
解答例:
numbers = [1, 2, 3, 4, 5] total = sum(numbers) print(total) # 出力: 15
解説: sum() 関数を使ってリスト内の数値の合計を計算しています。
Explanation: The built-in sum() function provides a convenient way to calculate the sum of all numbers in a list. It's much more concise than manually iterating through the list and adding up the elements.
まとめ
この記事では、Python のリストを活用した練習問題 10 選を紹介しました。これらの問題を解くことで、リストの基本的な操作から応用までを習得し、Python プログラミングのスキルアップに繋がるはずです。
リストは Python で非常に重要なデータ構造であり、様々な場面で活用されます。ぜひ、これらの練習問題を参考に、さらに多くのリストに関する知識を深めてください。
参照先:
このブログ記事が、あなたの Python プログラミング学習の一助となれば幸いです。
