List operations in Python : Ways to insert elements

Lists are one of the best data structures to use. Storing and extracting values from it is a breeze (most of the time). Python has a huge number of concepts and functions that work on the lists to maintain, update and extract data. List splicing, sorting , appending , searching , inserting and removing data are some of the operations that can be performed.

Among all these, I found two methods similar. The append() and the extend() . What these basically do is put elements at the end of a list.But they do have a striking difference. for example consider a list:

>>> list_sample =  [1, ‘name’, 2, 3, ‘True’]

What the append() does is, puts whatever item which is specified,into the list along with the item’s data structure. SO on the list_sample if we append another list ,say [‘a’ , ‘b’ ,’c’] we get:

>>>list_sample.append( [‘a’ , ‘b’ ,’c’])
>>> [1, ‘name’ , 2, 3, ‘True’, [‘a’ , ‘b’, ‘c’]

The append() here, has stored the entire list in sample_list as a single list item.

On the other hand, lets use extend() on list_sample. We shall extend the list_sample with another list [‘d’, ‘e’, ‘f’].

>>>list_sample.extend([‘d’, ‘e’, ‘f’])
>>> [1, ‘name’, 2, 3, ‘True’, ‘d’, ‘e’, ‘f’]

here extend() has extracted each value from the list ([‘d’, ‘e’, ‘f’] ) and inserted them individually at the end of sample_list.

Other ways to add elements in a list is by using the + (plus) operator. for example on the same defined list ,list_sample , we shall add 3 elements [‘False’, 9 , ‘h’]

>>>list_sample = list_sample + [‘False’, 9 , ‘h’]
>>>[1, ‘name’, 2, 3, ‘True’, ‘False’, 9 , ‘h’]

Elements can be added into the list at a particular position by making use of the insert() function. It takes in 2 arguments as inputs, the first specifies the position to be inserted in and second specifies the element to be inserted.

>>>[1, ‘name’, 2, 3, ‘True’]
>>>[1, ‘name’, 2, 3, ‘value’,  ‘True’]

So the string, ‘value’ is inserted at the position 4 (index 3) in sample_list.

These were some of the ways in which elements can be added into a list. Different methods are used in different situations to add the elements efficiently and quickly. That is, a single method is not relied upon to get the job done always.