C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This is the shortest syntax form. It requires only a list reference and three characters.
Python program that copies list
# A list:
list1 = [10, 20, 30]
# Copy list1 with slice syntax.
list2 = list1[:]
# Modify list2.
list2[0] = 0
print(list1)
print(list2)
Output
[10, 20, 30]
[0, 20, 30]
Note: This approach requires two lines. It is also less efficient. Please see the benchmark section.
Python program that uses extend, copies list
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)
Output
[10, 20, 30]
[0, 20, 30]
List: The list contains five numbers. We use while-loops to repeatedly copy those five elements.
WhileResult: Taking a slice to copy a list is faster. It required just 4.7 seconds, versus 5.3 for the extend method version.
Python program that times list copying
import time
list1 = [100, 200, 300, 400, 500]
print(time.time())
# Version 1: slice
i = 0
while i < 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())
Output
1395252155.968703
1395252160.704971 Slice = 4.736 s
1395252166.045275 Extend = 5.340 s