Sets and lists are handled differently in Python, and there seems to be no uniform way to work with both. For example, adding an item to a set
is done using the add
method, and for the list
it is done using the append
method. I am aware that there are different semantics behind this, but there are also common semantics there, and often an algorithm that works with some collection cares more about the commonalities than the differences. The C++ STL shows that this can work, so why is there no such concept in Python?
Edit: In C++ I can use an output_iterator
to store values in an (almost) arbitrary type of collection, including lists and sets. I can write an algorithm that takes such an iterator as argument and writes elements to it. The algorithm then is completely agnostic to the kind of container (or other device, may be a file) that backs the iterator. If the backing container is a set that ignores duplicates, then that is the decision of the caller. My specific problem is, that it has happened several times to me now that I used for instance a list
for a certain task and later decided that set
is more appropriate. Now I have to change the append
to add
in several places in my code. I am just wondering why Pyhton has no concept for such cases.