Copy list. A list references a region of memory. When assigned, the list reference itself is copied. In Python we can instead copy elements into a new list.
Extend. Next, we use the extend method to copy a list. We first need to allocate a new, empty list. Then we extend that empty list (list2) with the original list.
Note This approach requires two lines. It is also less efficient. Please see the benchmark section.
list1 = [10, 20, 30]
# Create empty list, then extend it.
list2 = []
list2.extend(list1)
# The lists are separate.
list2[0] = 0
print(list1)
print(list2)[10, 20, 30]
[0, 20, 30]
Performance. Here we consider performance of list copying. The list contains five numbers. We use while-loops to repeatedly copy those five elements.
Version 1 This Python code tests the slice syntax. An entire list is copied with by using an unspecified start and end.
Version 2 This code uses the extend method (after creating an empty list). We repeat these operations ten million times.
Result Taking a slice to copy a list is faster. It required just 4.7 seconds, versus 5.3 for the extend method version.
import time
list1 = [100, 200, 300, 400, 500]
print(time.time())
# Version 1: slice
i = 0
while < 10000000:
list2 = list1[:]
i += 1
print(time.time())
# Version 2: extend
i = 0
while i < 10000000:
list2 = []
list2.extend(list1)
i += 1
print(time.time())1395252155.968703
1395252160.704971 Slice = 4.736 s
1395252166.045275 Extend = 5.340 s
Summary. A full-list slice is a good way to copy a list. It requires the least amount of syntax. And it performs faster than the alternative approach that uses the extend method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 22, 2021 (image).