Skip to content
Worked Examples · Example 9.5

Q.Example 9.5: Copy a list using the copy() function of the python library copy (Method 3, newList = copy.copy(oldList)) — import copy and create a copy of list1 = [1,2,3,4,5] with list2 = copy.copy(list1).

Uttar Pradesh UpmspTextbookSubjective· 2mImportance★★★★★est
35% · 9/26 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Import the copy module and call copy.copy(oldList) — it returns a new list object with the same elements (a shallow copy), the third NCERT method of copying a list.

The idea (copying via the copy module). Python's standard library ships a module named copy whose copy() function produces a shallow copy of any object — for a list, a new outer list holding references to the same elements. It behaves like list1[:] and list(list1), but the module also offers copy.deepcopy() when nested structures must be duplicated all the way down.

Program

import copy               # the copy module must be imported first

list1 = [1, 2, 3, 4, 5]
list2 = copy.copy(list1)  # Method 3: shallow copy via the library

print("list1:", list1)
print("list2:", list2)
print("Same object?", list2 is list1)

# prove independence
list2[4] = 500
print("After list2[4] = 500")
print("list1:", list1)
print("list2:", list2)

Expected output

list1: [1, 2, 3, 4, 5]
list2: [1, 2, 3, 4, 5]
Same object? False
After list2[4] = 500
list1: [1, 2, 3, 4, 5]
list2: [1, 2, 3, 4, 500]

Key points

  • import copy is required; forgetting it raises NameError (and list.copy() the method is a different, also valid, route). …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.