# 如何在 Python 中串聯兩個或多個列表

``````list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
``````

## `+` 列表串聯方法

`+` 運算子可以連線兩個列表並返回一個新列表。

``````>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = list1 + list2
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]
``````

## `+=` 串聯方法

`+=` 與上述方法類似，但是它將在列表就位之前更改列表中的資料。

``````>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1 += list2
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
``````

## `itertools.chain` 方法

`itertools` 模組中的 `chain` 將連續序列視為一個序列

``````>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> import itertools
>>> result = list(itertools.chain(list1, list2))
[1, 2, 3, 4, 5, 6, 7, 8]
``````
Information
`itertools.chain` 有一個備用建構函式- `intertools.chain.from_iterable()`。它有一個可迭代的引數，其輸入是被懶惰評估的。

## `extend()` 方法

Python 列表 `extend` 方法通過附加來自可迭代物件的元素來擴充套件列表。

``````>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
``````

## `[*a, *b]``unpack` 方法

PEP-0448 中所述，從 Python 3.5 擴充套件了諸如`*`可迭代 `unpack` 運算子和`**`字典 `unpack` 運算子之類的 `unpack` 方法。

``````>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = [*list1, list2]
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]
``````

Warning

``````>>> A = [1,2,3]
>>> B = [4,5,6]
>>> C = [7,8,9]
>>> [*t for t in [A,B,C]]
SyntaxError: iterable unpacking cannot be used in comprehension
``````

## まとめ

`a + b` No
`list(intertools.chain(a,b))` >= 2.3 No
`[*a, *b]` >= 3.5 No
`a += b` Yes
`a.extend(b)` Yes

Aditya Raj is a highly skilled technical professional with a background in IT and business, holding an Integrated B.Tech (IT) and MBA (IT) from the Indian Institute of Information Technology Allahabad. With a solid foundation in data analytics, programming languages (C, Java, Python), and software environments, Aditya has excelled in various roles. He has significant experience as a Technical Content Writer for Python on multiple platforms and has interned in data analytics at Apollo Clinics. His projects demonstrate a keen interest in cutting-edge technology and problem-solving, showcasing his proficiency in areas like data mining and software development. Aditya's achievements include securing a top position in a project demonstration competition and gaining certifications in Python, SQL, and digital marketing fundamentals.

GitHub