Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use .copy() method of a subclass of the list object in Python 2.x?

I’m trying to use the .copy() method on a list subclass, but Python 2 is saying the copy() method doesn’t exists.

class MyList(list):
    pass
    
mylist = MyList()
mylist.append(1)
mylist.append("two")

print(str(mylist[0])  + " " + mylist[1])
mylist2 = mylist.copy()
mylist2.append("C")
print(str(mylist2[0]) + " " + mylist2[1] + " " + mylist2[2])

Python 2.6 result:

> python foo.py
1 two
Traceback (most recent call last):
  File "foo.py", line 48, in <module>
    mylist2 = mylist.copy()
AttributeError: 'MyList' object has no attribute 'copy'

Python 3.11 result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 two
1 two C

(Please don’t simply tell me to upgrade to Python 3; we have our reasons.)

Note: Although similar, this is not a duplicate of
this question, because that question is asked and answered in the Django context, and this is straight Python. Also, the suggested answer to that question is not as comprehensive as the accepted answer here.

>Solution :

In Python 2.x, the copy method does not exist for lists. You can achieve the desired result by creating a new instance of your custom list class (MyList) and populating it with the elements from the original list

class MyList(list):
pass

mylist = MyList()
mylist.append(1)
mylist.append("two")

print(str(mylist[0]) + " " + mylist[1])

# Create a new instance of MyList and populate it with elements from mylist
mylist2 = MyList(mylist)
mylist2.append("C")
print(str(mylist2[0]) + " " + mylist2[1] + " " + mylist2[2])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading