The complexity of len()
with regards to sets and lists is equally O(1). How come it takes more time to process sets?
~$ python -m timeit \"a=[1,2,3,
The relevant lines are http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup#l640
640 static Py_ssize_t
641 set_len(PyObject *so)
642 {
643 return ((PySetObject *)so)->used;
644 }
and http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup#l431
431 static Py_ssize_t
432 list_length(PyListObject *a)
433 {
434 return Py_SIZE(a);
435 }
Both are only a static lookup.
So what is the difference you may ask. You measure the creation of the objects, too. And it is a little more time consuming to create a set than a list.