How to concatenate two lists in Python?

How do I concatenate two lists in Python?

Example:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

Expected outcome:

>>> joinedlist
[1, 2, 3, 4, 5, 6]

You can use the + operator to combine them:

listone = [1,2,3]
listtwo = [4,5,6]

mergedlist = listone + listtwo

Output:

>>> mergedlist
[1,2,3,4,5,6]

It's also possible to create a generator that simply iterates over the items in both lists. This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
   # do something with each list item

您可以使用集合来获取唯一值的合并列表

mergedlist = list(set(listone + listtwo))
链接地址: http://www.djcxy.com/p/3134.html

上一篇: 如何克隆或复制列表?

下一篇: 如何在Python中连接两个列表?