Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Various list concatenation method and their performance

I was working on an algorithm and in that, we are trying to write every line in the code such that it adds up a good performance to the final code.

In one situation we have to add lists (more than two specifically). I know some of the ways to join more than two lists also I have looked upon StackOverflow but none of the answers are giving account on the performance of the method.

Can anyone show, what are the ways we can join more than two lists and their respective performance?

Edit : The size of the list is varying from 2 to 13 (to be specific). Edit Duplicate : I have been specifically asking for the ways we can add and their respected questions and in duplicate question its limited to only 4 methods

like image 772
Paul kingser Avatar asked Jun 15 '19 16:06

Paul kingser


People also ask

Which method is used to concatenate the list?

chain() method to concatenate lists.

How do you concatenate 5 lists in Python?

You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object.

What do you mean by concatenation in list explain with example?

What Is Concatenation? Concatenation of lists is an operation where the elements of one list are added at the end of another list. For example, if we have a list with elements [1, 2, 3] and another list with elements [4, 5, 6] .


1 Answers

There are multiples ways using which you can join more than two list.

Assuming that we have three list,

a = ['1']
b = ['2']
c = ['3']

Then, for joining two or more lists in python,

1) You can simply concatenate them,

 output = a + b + c

2) You can do it using list comprehension as well,

res_list = [y for x in [a,b,c] for y in x] 

3) You can do it using extend() as well,

a.extend(b)
a.extend(c)
print(a)

4) You can do it by using * operator as well,

res = [*a,*b,*c]

For calculating performance, I have used timeit module present in python.

The performance of the following methods are;

4th method < 1st method < 3rd method < 2nd [method on the basis of time]

That means If you are going to use " * operator " for concatenation of more than two lists then you will get the best performance.

Hope you got what you were looking for.

Edit:: Image showing performance of all the methods (Calculated using timeit)

enter image description here

like image 105
0xPrateek Avatar answered Oct 12 '22 06:10

0xPrateek