How do I concatenate two lists in Python?

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

    So there are two easy ways.

    1. Using +: It creates a new list from provided lists

    Example:

    In [1]: a = [1, 2, 3]
    
    In [2]: b = [4, 5, 6]
    
    In [3]: a + b
    Out[3]: [1, 2, 3, 4, 5, 6]
    
    In [4]: %timeit a + b
    10000000 loops, best of 3: 126 ns per loop
    
    1. Using extend: It appends new list to existing list. That means it does not create a separate list.

    Example:

    In [1]: a = [1, 2, 3]
    
    In [2]: b = [4, 5, 6]
    
    In [3]: %timeit a.extend(b)
    10000000 loops, best of 3: 91.1 ns per loop
    

    Thus we see that out of two of most popular methods, extend is efficient.

提交回复
热议问题