Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iter() time complexity?

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!

like image 734
tooesy Avatar asked Oct 08 '17 01:10

tooesy


People also ask

What is ITER () in Python?

python iter() method returns the iterator object, it is used to convert an iterable to the iterator. Syntax : iter(obj, sentinel) Parameters : obj : Object which has to be converted to iterable ( usually an iterator ). sentinel : value used to represent end of sequence.

What is the time complexity of enumerate?

Benefit of Using Enumerate index is that it has a complexity of O(n) which means you'll be traversing the list more than a couple of times(also considering the for loop itself), and it then returns the starting index of a given item, which means you'll get incorrect results for lists with duplicate items.

Does enumerate increase time complexity?

@10'004: enumerate() may work with infinite generators and therefore it does not copy its input. Though it won't change the time complexity even if it did (for a finite input).

What does ITER and next do in Python?

The __iter__() method returns the iterator object itself. If required, some initialization can be performed. The __next__() method must return the next item in the sequence. On reaching the end, and in subsequent calls, it must raise StopIteration .


1 Answers

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


See also Retrieve an arbitrary key from python3 dict in O(1) time for an extended answer on .__next__()!

like image 131
ti7 Avatar answered Oct 08 '22 14:10

ti7