Mylist.clear() is not the same as mylist = [ ]

I had a for loop where one small_list got appended to the some bigger list_of_lists.

Throughout the cycle small_list eventually needed to be emptied.
So I tried the .clear() method, but it was a bad idea; because by clearing the data from small_list it had also cleared the data that were previously appended in list_of_lists !..

I know that it is due to some ‘object’ or ‘memory’ management. But isn’t it a bit messy?

Anyway, I now know that next time I need just “reinstatiate” the list by
mylist = [ ]
mylist = list()

Thank you.

When you do mylist.clear() you modify the existing object mylist. With mylist = [] you create a new list and bind it to the name mylist.


Python is really, really an object-based language. When you append littlelist to biglist, you append a reference to littlelist. There is NO copying of the list. If you modify littlelist, you modify it regardless of how you access it. If you extend biglist with littlelist, you append references to all the items in littlelist.

A list is like an online club roster that contains names that refer to people. If you are a member of several clubs and you get sick, you are sick regardless of which club roster is used to contact you.

1 Like

Python expects you to know the difference between assigning a reference, and copying.

If you want to copy, use list_.append(list2[:]) or something (for a shallow copy).

When I was in school, I was taught that a language like Python is object oriented (because it has inheritance), while a language like Ada was object based (because it has objects but no inheritance).

I have seen ‘object-oriented’ defined as meaning that one must write everything in overt classes, while Python lets one write procedural and functional code in which the object nature of Python seems hidden – until one does things like the OP did. I don’t care much about the nomenclature, as opposed to computational behavior. My point was the same as yours, which is that at this point, one must know that one appends object references, rather than values. Hence the aliasing that the OP experienced.