The copy() method of deque class in Python

The copy() method of deque class returns a new deque object with shallow copies of the elements.That is the deque object itself is a new object but the contents are copied from the original deque

Deque Updated 18 Mar 2017 1 min read

Method Name

copy

Method Signature

copy

Method Overview

  • The copy() method of deque class in python returns copy of a deque object.
  • The returned deque object is a new object where as the elements present in the new deque object are just copied from the original deque. ie., elements are shallow copied
  • The example below verifies the shallow copying process of the copy() method by printing the ids of the deque objects the elements present in them.

Copying of a deque

Example

python
import collections

t1 = (1,2,3,4,5)

d1 = collections.deque(t1)

d2 = d1.copy()

print("d1 contents:")

print(d1)

print("d2 id:")

print(id(d1))

print("d2 contents:")

print(d2)

print("d2 id:")

print(id(d2))

print("checking the first element of d1 and d2 are shallow copies:")

print(id(d1[0]))

print(id(d2[0]))

Output

Output
d1 contents:

deque([1, 2, 3, 4, 5])

d2 id:

4300761504

d2 contents:

deque([1, 2, 3, 4, 5])

d2 id:

4301821744

checking the first element of d1 and d2 are shallow copies:

4297623936

4297623936