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!
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.
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.
@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).
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 .
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__()
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With