Python: Copy Nested List, Shallow/Deep Copy

By Xah Lee. Date: . Last updated: .

Copying List by Reference

If you do this list_a = list_b, that'll copy a reference. That means: modifying one list also modifies the other.

# python 3

list_a = [3, 4, 5]
list_b = list_a
list_a[0] = 7
print(list_b )
# [7, 4, 5]

Check Equality of 2 Objects

You can check by using the “id” function. The id(obj) returns the object's memory address.

# python 3

aa = [3, 4, 5]
bb = aa

print(id(aa))
# 4477411144

print(id(aa) == id(bb))
# True

Copy Flat List Using List Slice

You can make a copy by list_b = list_a[:]. When the first index are omitted, it default to 0. When the ending index is omitted, it default to length of the list.

# python 3

list_a = [3,4,5]
list_b = list_a[:]

print(id(list_a) == id(list_b))
# False

print(list_a == list_b)
# True

Copy Flat List Using 「.extend()」

# python 3

list_a = [3, 4, 5]
list_b = []
list_b.extend(list_a)

print(id(list_a) == id(list_b))
# False

print(list_a == list_b)
# True

Copy Flat List Using 「list()」

The best way to copy flat list is

lst2 = list(lst)

# python 3

list_a = [3, 4, 5]
list_b = list(list_a)

print(id(list_a) == id(list_b))
# False

print(list_a == list_b)
# True

Copying Nested List, Deep Copy

Use the module “copy” to make a truely independent copy of a list.

# python 3

import copy

list_a = [[3, 4], [5, 6, [7, 8]]]
list_b = copy.deepcopy(list_a)

list_a[0][1] = 9

print(list_a)
# [[3, 9], [5, 6, [7, 8]]]

print(list_b)
# [[3, 4], [5, 6, [7, 8]]]

What's Shallow Copy?

All the following only does shallow copy:

They only create a copy on the 0th level. That's called shallow copy. The elements of a nested element are copied by reference.

# python 3

# example of shallow copy. Changing a nested element still effect the original list

aa = [[3, 6], [5, [8]]]
bb = list(aa)

aa[0][1] = 9

print(aa)
# [[3, 9], [5, [8]]]

print(bb)
# [[3, 9], [5, [8]]]

See also: Python: dict={} vs dict.clear().

Python List, Tuple, Dictionary

  1. List Basics
  2. Loop Thru List
  3. Map f to List
  4. Copy Nested List
  5. List Comprehension
  6. List Methods
  7. Sort
  8. Dictionary
  9. Loop Thru Dict
  10. Dict Methods
  11. Tuple
  12. Sets, Union, Intersection

Python Semantic Bad

  1. Why List Comprehension is Bad
  2. Python 3: Map with Side Effect Doesn't Work If Result is Not Used
  3. The Idiocy of Python's Function Parameter Specification
  4. Python Scope Complexity, Shallow Copy, Deep Copy, Circular List, and the Garbage Underneath Computer Languages
  5. Python: dict={} vs dict.clear()
  6. Python: Get Number of Arguments of Function
  7. Python: Copy Nested List, Shallow/Deep Copy
  8. Python: Keyword Argument Default Value Unstable
  9. Python: Append String in Loop
  10. FCK Python: String Methods, Functions, Slashes and Backslashes
  11. Python Bitwise Invert Oddity
  12. From Why Not Ruby to FCK Python, Hello Ruby
  13. Why Learn Lisp When There Are Perl and Python

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation