Pythonリスト操作におけるappend()メソッドの実用的な活用事例15選

基本的な操作

1. 単一要素の追加

data_list = [10, 20, 30]
data_list.append(40)
print(data_list)  # 出力: [10, 20, 30, 40]

2. 反復処理によるリスト構築

result = []
for j in range(1, 6):
    result.append(j)
print(result)  # 出力: [1, 2, 3, 4, 5]

3. ユーザ入力の動的収集

inputs = []
user_value = ''
while user_value != 'exit':
    user_value = input("値を入力('exit'で終了): ")
    if user_value != 'exit':
        inputs.append(user_value)
print(inputs)

4. 関数戻り値の追加

def generate_value():
    return 100

values = []
values.append(generate_value())
print(values)  # 出力: [100]

ループと動的データ処理

5. ネストしたリストの追加

primary = ['a', 'b']
secondary = ['c', 'd']
primary.append(secondary)
print(primary)  # 出力: ['a', 'b', ['c', 'd']]

6. 数列生成パターン

sequence = [5, 8]
for _ in range(4):
    next_val = sequence[-1] + sequence[-2]
    sequence.append(next_val)
print(sequence)  # 出力: [5, 8, 13, 21, 34, 55]

7. 型制限付き入力処理

numeric_data = []
while True:
    try:
        val = int(input("数値を入力: "))
        numeric_data.append(val)
    except:
        break
print(numeric_data)

実践的応用例

8. APIレスポンス処理

import requests

response = requests.get('https://jsonplaceholder.typicode.com/users')
user_list = []
for user in response.json():
    user_list.append(user['name'])
print(user_list)

9. 簡易キュー実装

task_queue = []
task_queue.append('process_data')
task_queue.append('send_report')
current_task = task_queue.pop(0)
print(f"実行中: {current_task}")
print(f"残りタスク: {task_queue}")

10. 実行ログ記録

event_log = []
event_log.append("システム起動")
try:
    # 処理実行
    event_log.append("処理完了")
except Exception as error:
    event_log.append(f"エラー発生: {str(error)}")
print(event_log)

高度なテクニック

11. 条件付きリスト構築

original = [3, 7, 4, 9]
filtered = []
[filtered.append(x * 2) for x in original if x > 5]
print(filtered)  # 出力: [14, 18]

12. タプル変換処理

tuple_values = (15, 25, 35)
converted = []
for element in tuple_values:
    converted.append(element)
print(converted)  # 出力: [15, 25, 35]

13. ミュータブル引数操作

def add_element(item, container):
    container.append(item)

dynamic_list = []
add_element('first', dynamic_list)
add_element('second', dynamic_list)
print(dynamic_list)  # 出力: ['first', 'second']

14. シャローコピーの注意点

source = [1, [2, 3]]
duplicate = source.copy()
duplicate[1].append(4)
print(source)  # 出力: [1, [2, 3, 4]]

15. 大規模データ処理の最適化

import collections

large_data = collections.deque()
for i in range(1000000):
    large_data.append(i)
# dequeの方が大規模データ追加効率が良い

タグ: Python リスト append 可変シーケンス データ構造

6月27日 18:05 投稿