Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - JOIN TWO LIST


How to extend an existing List or join two Lists?


Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to insert a new List with two names 'Sia' and 'Andrew' at the end of the List.


There are two ways by which we can join or extend List.


  1. By using the '+' operator
  2. Using the 'extend( )' Function

At first let us see the Joining of two Lists using '+' operator.


Example :


x = ["Mohan", "Kriti", "Salim"]
y = ["Sia", "Andrew"]
z = x + y
print(z) 


Output :



  ['Mohan', 'Kriti', 'Salim', 'Sia', 'Andrew']

So, in the above code we have created a 'List' and initialised to the variable 'x'.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the List,


java_Collections

Also we have another List that contains, 'Sia' and 'Andrew'.


y = ["Sia", "Andrew"]

java_Collections

Next, we have used the '+' operator to add the the Lists 'x' and 'y'.


z = x + y

And the Lists 'x' and 'y' is joined and initialised to a new List 'z'.


java_Collections

And we get the below output,


['Mohan', 'Kriti', 'Salim', 'Sia', 'Andrew']

Let us rewrite the same example using the 'extend( )' Function.


Example :


x = ["Mohan", "Kriti", "Salim"]
y = ["Sia", "Andrew"]
x.extend(y)
print(x) 


Output :



  ['Mohan', 'Kriti', 'Salim', 'Sia', 'Andrew']

So, in the above code we have created a 'List' and initialised to the variable 'x'.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the List,


java_Collections

Also we have another List that contains, 'Sia' and 'Andrew'.


y = ["Sia", "Andrew"]

java_Collections

Next, we have used the 'extend( )' function to add the new List 'y' that contains 'Sia' and 'Andrew' at the end of the List 'x'.


x.extend(y)

And the List 'y' is joined with 'x'.


java_Collections

And we get the below output,


['Mohan', 'Kriti', 'Salim', 'Sia', 'Andrew']