Free cookie consent management tool by TermsFeed The copy() method of deque class in Python | Pythontic.com

The copy() method of deque class in Python

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:

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:

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

 


Copyright 2025 © pythontic.com