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




PYTHON - COPY FROM LIST


How to copy one List to the other ?


There are two ways by which we can copy one List to the other.


  1. Using the method 'List( )'
  2. Using the method 'copy( )'

Let us look at the first way using the 'List( )' method.


Example :


x = ["Mohan", "Kriti", "Salim"]
y = List(x)
print("The Copied List is ",y) 


Output :



  The Copied List is ['Mohan', 'Kriti', 'Salim']

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

Then we have used the 'List( )' method to take the List 'x' as parameter and create a new List that would be the exact copy of 'x' .


Then assign it to 'y' .


y = List(x)

java_Collections

And we get the below output ,


The Copied List is ['Mohan', 'Kriti', 'Salim']

Now , let us look at the second way of copying a List using 'copy( )' method.


Example :


x = ["Mohan", "Kriti", "Salim"]
y = x.copy()
print("The Copied List is ",y) 


Output :



  The Copied List is ['Mohan', 'Kriti', 'Salim']

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

Then we have used the 'copy( )' method that would create an exact copy of 'x' . And assign it to 'y' .


y = x.copy()

java_Collections

And we get the below output ,


The Copied List is ['Mohan', 'Kriti', 'Salim']

Note : Do not use the '=' operator to copy a List to the other(i.e. If there are two Lists 'x' and 'y'. Do not use y = x). Because in that case any changes made to the List 'x' will be reflected in the copied List 'y'.