0
0
PythonHow-ToBeginner · 3 min read

How to Copy a List in Python: Simple Methods Explained

To copy a list in Python, you can use list.copy(), slicing like list[:], or the list() constructor. These methods create a new list with the same elements, avoiding changes to the original list when you modify the copy.
📐

Syntax

Here are the common ways to copy a list in Python:

  • new_list = old_list.copy() - uses the copy() method.
  • new_list = old_list[:] - uses slicing to copy all elements.
  • new_list = list(old_list) - uses the list() constructor to create a copy.

Each creates a new list with the same items as the original.

python
old_list = [1, 2, 3]

# Using copy() method
new_list1 = old_list.copy()

# Using slicing
new_list2 = old_list[:]

# Using list() constructor
new_list3 = list(old_list)
💻

Example

This example shows how changing the copied list does not affect the original list.

python
original = [10, 20, 30]
copied = original.copy()
copied.append(40)

print("Original list:", original)
print("Copied list:", copied)
Output
Original list: [10, 20, 30] Copied list: [10, 20, 30, 40]
⚠️

Common Pitfalls

A common mistake is to assign a list directly like new_list = old_list. This does not copy the list but makes both variables point to the same list. Changes to one will affect the other.

Also, these methods create a shallow copy. If the list contains other lists (nested lists), the inner lists are not copied but shared.

python
old_list = [[1, 2], [3, 4]]

# Wrong: just assignment
new_list = old_list
new_list[0].append(99)
print("Old list after change:", old_list)

# Right: shallow copy
new_list2 = old_list.copy()
new_list2[0].append(100)
print("Old list after shallow copy change:", old_list)
Output
Old list after change: [[1, 2, 99], [3, 4]] Old list after shallow copy change: [[1, 2, 99, 100], [3, 4]]
📊

Quick Reference

MethodDescriptionExample
copy()Creates a shallow copy of the listnew_list = old_list.copy()
SlicingCopies all elements using slice syntaxnew_list = old_list[:]
list()Creates a new list from an iterablenew_list = list(old_list)
AssignmentDoes NOT copy, just references the same listnew_list = old_list

Key Takeaways

Use list.copy(), slicing, or list() to create a new list copy.
Direct assignment copies only the reference, not the list itself.
These methods create shallow copies; nested lists remain shared.
Modifying the copied list does not affect the original list.
For deep copies of nested lists, use the copy module's deepcopy.