w3resource

Python List: copy() Method

copy() Method

The copy() method returns a copy of a given list.

Visual Explanation:

Python List: copy() method

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



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]