How do I concatenate two lists in Python?

前端 未结 25 1957
时光取名叫无心
时光取名叫无心 2020-11-21 06:18

How do I concatenate two lists in Python?

Example:

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

Expected outcome:

>&g         


        
25条回答
  •  别跟我提以往
    2020-11-21 07:01

    It's worth noting that the itertools.chain function accepts variable number of arguments:

    >>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
    >>> [i for i in itertools.chain(l1, l2)]
    ['a', 'b', 'c']
    >>> [i for i in itertools.chain(l1, l2, l3)]
    ['a', 'b', 'c', 'd', 'e', 'f']
    

    If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

    >>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
    >>> [i for i in itertools.chain.from_iterable(il)]
    ['a', 'b', 'c', 'd', 'e', 'f']
    

提交回复
热议问题