Python iter() time complexity?

核能气质少年 提交于 2020-06-27 09:56:27

问题


I was looking up an efficient way to retrieve an (any) element from a set in Python and came across this method:

anyElement = next(iter(SET))

What exactly happens when you generate an iterator out of a container such as a set? Does it simply create a pointer to the location of the object in memory and move that pointer whenever next is called? Or does it convert the set to a list then create an iterator out of that?

My main concern is if it were the latter, it seems iter() would be an O(n) operation. At that point it would be better to just pop an item from the set, store the popped item in a variable, then re-insert the popped item back into the set.

Thanks for any information in advance!


回答1:


sets are iterable, but don't have a .__next__() method, so iter() is calling the .__iter__() method of the set instance, returning an iterable which does have the __next__ method.

As this is a wrapper around an O(1) call, it will operate in O(1) time once declared

https://wiki.python.org/moin/TimeComplexity



来源:https://stackoverflow.com/questions/46626669/python-iter-time-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!