What is the most efficient way to concatenate two lists list_a and list_b when:
list_bitems have to be placed beforelist_aitems- the result must be placed in
list_a
I have 4 possibilities in mind:
# 1
list_a = list_b + list_a
# 2
for item in list_b:
list_a.insert(0, item)
# 3
for item in self.list_a:
list_b.append(item)
list_a = list_b
# 4
list_a[0:0] = list_b
Thanks!
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.
t1:
t2:
t3:
t4: