Python List: copy() Method
copy() Method
The copy() method returns a copy of a given list.
Visual Explanation:
Syntax:
new_list = list.copy()
Parameter: No parameters
Return Value from clear() method
Returns a new list. It doesn't modify the original list.
Equivalent Command of copy() method:
a[:]
Example 1: Copying a List
# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:")
print(colors)
print("Copying the said list:")
new_colors = colors.copy()
print("Add an element to list:")
new_colors.append('White')
print("New list:",new_colors)
Output:
Original list: ['Red', 'Green', 'Black'] Copying the said list: Add an element to list: New list: ['Red', 'Green', 'Black', 'White']
Example 2: Copy List using slicing syntax
# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:")
print(colors)
print("Copying the said list:")
new_colors = colors[:]
print("Add an element to list:")
new_colors.append('White')
print("New list:",new_colors)
Output:
Original list: ['Red', 'Green', 'Black'] Copying the said list: Add an element to list: New list: ['Red', 'Green', 'Black', 'White']
Python Code Editor:
Previous: Python List clear() Method.
Next: Python List count() Method.
Test your Python skills with w3resource's quiz
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics