B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Copy Lists in Python | LiveCodeProgramming
Python Installation First Python Program Control Flow if...else nested if else match-case logical-operators for loops while loops break / continue Functions Defining Functions Function Arguments Function return value Lambda Function Recursion Exception Handling Exception Handling Try Except Else and Finally Raise Exception Custom Exceptions File Handling File in python Read File Write File Append File Delete File Exception Handling

Copying Lists in Python

There are multiple ways to copy lists in Python. Some methods create real copies, others just references. Let's explore them with examples.

Python में list को copy करने के कई तरीके होते हैं। कुछ method असली copy बनाते हैं और कुछ reference। चलिए इन्हें उदाहरण सहित समझते हैं।

1. Assignment (Reference)
original = ["abhishek", "badri"]
copied = original
copied[0] = "devendra"
print(original)
Output:
['devendra', 'badri']
2. Using list() Constructor
original = ["abhishek", "badri"]
copied = list(original)
copied[0] = "devendra"
print(original)
Output:
['abhishek', 'badri']
3. Using Slicing [:]
original = ["abhishek", "badri"]
copied = original[:]
copied[0] = "chandrakant"
print(original)
Output:
['abhishek', 'badri']
4. Using copy() Method
original = ["abhishek", "badri"]
copied = original.copy()
copied[0] = "devendra"
print(original)
Output:
['abhishek', 'badri']
5. Using list comprehension
original = ["abhishek", "badri"]
copied = [item for item in original]
copied[1] = "chandrakant"
print(original)
Output:
['abhishek', 'badri']
6. Using copy module (deepcopy)
import copy
original = [["abhishek"], ["badri"]]
copied = copy.deepcopy(original)
copied[0][0] = "devendra"
print(original)
Output:
[['abhishek'], ['badri']]