Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Lists
  6. Cloning

Cloning

Creating a copy of the same list of elements with two different memory locations is called cloning

Changes in one list will not affect locations of another list

Cloning is a process of making a copy of the list without modifying the original list

  • Slicing
  • list( )
  • copy( )

Copying the list using slice operator

orig_list = [10,1,2,7,5]
new_list = orig_list[:]
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)

Output

Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]

Copying the list using list( ) method

orig_list = [10,1,2,7,5]
new_list = list(orig_list)
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)

Output

Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]

Copying the list using copy( ) method

orig_list = [10,1,2,7,5]
new_list = orig_list.copy()
print("Original list:", orig_list)
print("New list:", new_list)
orig_list[0] = 100
print("After changing, Original list:", orig_list)
print("After changing, New list:", new_list)

Output

Original list: [10, 1, 2, 7, 5]
New list: [10, 1, 2, 7, 5]
After changing, Original list: [100, 1, 2, 7, 5]
After changing, New list: [10, 1, 2, 7, 5]

Loading

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments