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.
list1 = [100, 200, 300, 400, 500]
# Version 1: slice
i = 0
while < 10000000:
list2 = list1[:]
i += 1
# Version 2: extend
i = 0
while i < 10000000:
list2 = 
i += 1
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 22, 2021 (image).