- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How to clone or copy a list in Python?
In Python, assignment operator doesn’t create a new object, rather it gives another name to already existing object. This can be verified by id() function
>>> L1 = [1,2,3,4] >>> L2 = L1 >>> id(L1) 185117137928 >>> id(L2) 185117137928
To actually copy a list, following methods can be used.
Slice operator: Two operands of slice operator are index of start and end of slice. If not explicitly used, both default to start end of sequence. We can take advantage of this feature
>>> L1 = [1,2,3,4] >>> L2 = L1[:] >>> L1 [1, 2, 3, 4] >>> L2 [1, 2, 3, 4] >>> id(L1) 185117025160 >>> id(L2) 185117171592
Another method is to use built-in list() method
>>> L1 =[ 1,2,3,4] >>> L2 = list(L1) >>> L1 [1, 2, 3, 4] >>> L2 [1, 2, 3, 4] >>> id(L1) 185117295816 >>> id(L2) 185117209352
The copy module of Python’s standard library contains functions for shallow and deep copy of objects. While deep copy is nested copying, in shallow copy, inner list copied by reference only.
>>> import copy >>> L1 = [1,2,3,4] >>> L2 = copy.copy(L1) >>> L1 [1, 2, 3, 4] >>> L2 [1, 2, 3, 4] >>> id(L1) 185117025160 >>> id(L2) 185117295880 >>> L3=copy.deepcopy(L1) >>> L3 [1, 2, 3, 4] >>> id(L3) 185117304328
- Related Articles
- Python program to clone or copy a list.
- How to copy or clone a C# list?
- How to clone or copy a list in Kotlin?
- C# program to clone or copy a list
- How to copy or clone a Java ArrayList?
- How to Clone a List in Java?
- Python How to copy a nested list
- How to clone a generic list in C#?
- How to copy a list to another list in Java?
- How to copy a file to a remote server in Python using SCP or SSH?
- Copy list with random Pointer in Python
- How to copy a List collection to an array?
- How do you copy a list in Java?
- How to Clone a Map in Java
- How to copy a table in MySQL using Python?