• Register
2 votes
30 views

Problem:

I am quite a noob in python programming. I just started learning how to code with python. Now I am working with python list and trying to handle it. Could anybody help me here by telling me, how to copy a list in python, please?

I would appreciate it the most.

12 7 7
15,250 points

1 Answer

2 votes
 
Best answer

Solution:

There are multiple ways to do the copy/clone a python list

  • Using slicing technique
  • Using the extend() method
  • Using the list() method
  • Using the method of Shallow Copy
  • Using list comprehension
  • Using the append() method
  • Using the copy() method
  • Using the method of Deep Copy

Among all of them, the first three are popular, and the fastest way to cloning list.

Slicing Technique:

# Python program to copy or clone a list 
# Using the Slice Operator 
def Cloning(li1): 
    li_copy = li1[:] 
    return li_copy 
  
# Driver Code 
li1 = [4, 8, 2, 10, 15, 18] 
li2 = Cloning(li1) 
print("Original List:", li1) 
print("After Cloning:", li2) 

This is the fastest and easiest way to clone a list. This method used when we need to modify a list and keep a copy of an original list.

 

extend() Method:

# Python code to clone or copy a list 
# Using the in-built function extend() 
def Cloning(li1): 
    li_copy = [] 
    li_copy.extend(li1) 
    return li_copy 
  
# Driver Code 
li1 = [4, 8, 2, 10, 15, 18] 
li2 = Cloning(li1) 
print("Original List:", li1) 
print("After Cloning:", li2)

list() Method:

# Python code to clone or copy a list 
# Using the in-built function list() 
def Cloning(li1): 
	li_copy = list(li1) 
	return li_copy 

# Driver Code 
li1 = [4, 8, 2, 10, 15, 18] 
li2 = Cloning(li1) 
print("Original List:", li1) 
print("After Cloning:", li2)

This is the simplest way to make a clone of a list by using the built-in list() function.

13 9 6
94,240 points

Related questions

0 votes
1 answer 5 views
5 views
Problem: Is there any way to make copy of a list? Please suggest possibles examples.
asked Nov 2 Mubashi-Question 1.7k points
0 votes
1 answer 5 views
0 votes
1 answer 8 views
8 views asked Oct 23 Shaad Sh 800 points
0 votes
1 answer 4 views
0 votes
1 answer 8 views