How do I concatenate two lists in Python?

前端 未结 25 2005
时光取名叫无心
时光取名叫无心 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 06:41

    For cases with a low number of lists you can simply add the lists together or use in-place unpacking (available in Python-3.5+):

    In [1]: listone = [1, 2, 3] 
       ...: listtwo = [4, 5, 6]                                                                                                                                                                                 
    
    In [2]: listone + listtwo                                                                                                                                                                                   
    Out[2]: [1, 2, 3, 4, 5, 6]
                                                                                                                                                                                         
    In [3]: [*listone, *listtwo]                                                                                                                                                                                
    Out[3]: [1, 2, 3, 4, 5, 6]
    

    As a more general way for cases with more number of lists, as a pythonic approach, you can use chain.from_iterable()1 function from itertoold module. Also, based on this answer this function is the best; or at least a very food way for flatting a nested list as well.

    >>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> import itertools
    >>> list(itertools.chain.from_iterable(l))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    1. Note that `chain.from_iterable()` is available in Python 2.6 and later. In other versions, use `chain(*l)`.

提交回复
热议问题