What is the fastest way to merge two lists in python?

后端 未结 5 467
借酒劲吻你
借酒劲吻你 2020-12-10 10:49

Given,

list_1 = [1,2,3,4]
list_2 = [5,6,7,8]

What is the fastest way to achieve the following in python?

l         


        
相关标签:
5条回答
  • 2020-12-10 11:26

    If you are using python 3, there is one more way to do this and a little bit faster (tested only on python 3.7)

    [*list1, *list2]
    

    Benchmark

    from timeit import timeit
    x = list(range(10000))
    y = list(x)
    
    def one():
        x + y
    
    def two():
        [*x, *y]
    
    print(timeit(one, number=1000, globals={'x':x, 'y': y}))
    print(timeit(two, number=1000, globals={'x':x, 'y': y}))
    0.10456193100253586
    0.09631731400440913
    
    0 讨论(0)
  • 2020-12-10 11:29

    I tested out several ways to merge two lists (see below) and came up with the following order after running each several times to normalize the cache changes (which make about a 15% difference).

    import time
    c = list(range(1,10000000))
    c_n = list(range(10000000, 20000000))
    start = time.time()
    *insert method here* 
    print (time.time()-start)
    
    • Method 1: c.extend(c_n)

      • Representative result: 0.11861872673034668
    • Method 2: c += c_n

      • Representative result: 0.10558319091796875
    • Method 3: c = c + c_n

      • Representative result: 0.25804924964904785
    • Method 4: c = [*c, *c_n]

      • Representative result: 0.22019600868225098

    Conclusion Use += or .extend() if you want to merge in place. They are significantly faster.

    0 讨论(0)
  • 2020-12-10 11:31

    list_1 + list_2 does it. Example -

    >>> list_1 = [1,2,3,4]
    >>> list_2 = [5,6,7,8]
    >>> list_1 + list_2
    [1, 2, 3, 4, 5, 6, 7, 8]
    
    0 讨论(0)
  • 2020-12-10 11:38
    a=[1,2,3]
    b=[4,5,6]
    
    c=a+b
    print(c)
    

    OUTPUT:

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

    In the above code "+" operator is used to concatenate the 2 lists into a single list.

    ANOTHER SOLUTION:

     a=[1,2,3]
     b=[4,5,6]
     c=[] #Empty list in which we are going to append the values of list (a) and (b)
    
     for i in a:
         c.append(i)
     for j in b:
         c.append(j)
    
     print(c)
    

    OUTPUT:

    >>> [1, 2, 3, 4, 5, 6]
    
    0 讨论(0)
  • 2020-12-10 11:51

    You can just use concatenation:

    list = list_1 + list_2
    

    If you don't need to keep list_1 around, you can just modify it:

    list_1.extend(list_2)
    
    0 讨论(0)
提交回复
热议问题