How do I concatenate two lists in Python?

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

    If you can't use the plus operator (+), you can use the operator import:

    import operator
    
    listone = [1,2,3]
    listtwo = [4,5,6]
    
    result = operator.add(listone, listtwo)
    print(result)
    
    >>> [1, 2, 3, 4, 5, 6]
    

    Alternatively, you could also use the __add__ dunder function:

    listone = [1,2,3]
    listtwo = [4,5,6]
    
    result = list.__add__(listone, listtwo)
    print(result)
    
    >>> [1, 2, 3, 4, 5, 6]
    

提交回复
热议问题