2

if we want to construct a list from a set, we can do

[k for k in set] 

This is O(n) operation, meanwhile:

dict.keys() 

is O(1) according to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

Thus, as far as I know, dict is using set as its keys underlying data structure, is list(set) O(1)? And how is this implemented?

a = set(range(n)) s = list(a) # is this operation O(1)? 
3
  • 2
    What do you mean by list(set)? Note that dict.keys() returns a view, which is neither a list nor a set. Commented Apr 23, 2018 at 23:46
  • @Ry︁ that's in python3, python2 still returns a list. Commented Apr 23, 2018 at 23:50
  • 3
    Your document is about Python 3. The complexity of dict.keys() is O(n) in Python 2. Commented Apr 23, 2018 at 23:50

1 Answer 1

1

Thus, as far as I know, dict is using set as its keys underlying data structure.

Hmm, no not really. The opposite way around is a closer analogy: in the implementation, set is like a dict with all null values. The dict came first in Python, and set did not appear until Python 2.2 (July 2000) - see PEP 218.

Also worth mentioning that dict.keys() is O(1) since Python 3. In Python 2 it's O(n) and you should use dict.viewkeys() for the keys "view" (set-like interface).

is list(set) O(1)?

No, it's O(n) - just the same as the list comprehension.

And how is this implemented?

Sets support the iterator protocol.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.