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

后端 未结 5 466
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题