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

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

提交回复
热议问题