Python 2つのリスト(配列)を結合する

List を 結合するには 演算子「+」か、extend メソッド を使用します。

演算子「+」と extend メソッド の違い

# 演算子「+」
新しいリスト = リスト1 + リスト2

# extendメソッド
リスト1.extend(リスト2)

演算子「+」の使用方法

新しいリスト = リスト1 + リスト2

サンプルプログラム

次のサンプルコードは list1 と list2 を結合した newList を作成し、結果を表示しています。
# リストを2つ用意
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# list1 と list2 を結合し、新しいリストを作る
newList = list1 + list2

# 結果 = [1, 2, 3, 4, 5, 6]
print(f'newList = {newList}')

# list1 と list2 は変化なし
# list1 = [1, 2, 3]
# list2 = [4, 5, 6]
print(f'list1 = {list1}')
print(f'list2 = {list2}')
サンプルコードの実行結果
サンプルコードの実行結果

extendメソッド の使用方法

リスト1.extend(リスト2)

サンプルプログラム

次のサンプルコードは extendメソッドを使用して list1 の最後に list2 を結合しています。
# リストを2つ用意
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# list1 の末尾に list2 を追加
list1.extend(list2)

# 結果 = [1, 2, 3, 4, 5, 6]
print(f'list1 = {list1}')

# list2 は変化なし
# list2 = [4, 5, 6]
print(f'list2 = {list2}')
サンプルコードの実行結果
サンプルコードの実行結果

参考資料

検証環境