Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exactly are .values() and .keys() considered O(1)?

Couldnt track down a solid enough reasoning for why dictionary functions such as .values() and .keys() are considered to be O(1) in big O notation. (not sure if .items() is also considered O(1) )

like image 401
Vanessa Ventura Avatar asked Dec 18 '22 16:12

Vanessa Ventura


1 Answers

It is likely that the reference you found to .keys() and .values() (and .items()) being O(1) emphasized the performance because it is a contrast to Python 2, where those functions returned lists and required O(N) time to copy references to all the relevant objects out of the dictionary.

Iterating on the view objects returned by those methods in Python 3 will still take O(N) time, as there's no way to avoid visiting each item, since that's the whole point of iteration. The keys and items views do offer O(1) membership tests (e.g. (somekey, somevalue) in somedict.items()), which is a lot more efficient than searching for an item in a list.

like image 178
Blckknght Avatar answered Dec 20 '22 07:12

Blckknght