python list concatenation efficiency

前端 未结 6 1376
陌清茗
陌清茗 2020-12-16 13:07

What is the most efficient way to concatenate two lists list_a and list_b when:

  • list_b items have to be placed before
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 13:40

    Here's a graph of how the timings used in the answer of BigYellowCactus develop as the length of the lists increase. The vertical axis is the time required to initialize both lists and insert one in front of the other, in usec. The horizontal axis is the number of items in the lists.

    Asymptotic behaviour of the possibilities

    t1:

    list_a = list_b + list_a
    

    t2:

    for item in list_b:
        list_a.insert(0, item)
    

    t3:

    for item in list_a:
        list_b.append(item)
    list_a = list_b
    

    t4:

    list_a[0:0] = list_b
    

提交回复
热议问题