2025.10.18(更新日: 2025.10.18)
【Python】リスト2つを比較して、もう一方のリストに存在しない要素のリストを作成する
はじめに
a_listとb_listがある。
a_listにあって、b_listにない要素のリストを作成する。
ソースコード
not_in_others_list.py · ki-hi-ro/python@f07e63c
a_list = ['apple', 'banana', 'cherry', 'date']
b_list = ['banana', 'date', 'fig', 'grape']
not_in_b_list = [item for item in a_list if item not in b_list]
print("Items in a_list not in b_list:", not_in_b_list)
not_in_b_listはリスト内包表記で、a_listの中でb_listにないitemをリストにしている。
実行結果
Items in a_list not in b_list: ['apple', 'cherry']
a_listにあって、b_listにないitemが抽出された。
a_list = ['apple', 'banana', 'cherry', 'date']
b_list = ['banana', 'date', 'fig', 'grape']
コメントを残す