6

In Python, what are the running time and space complexities if a list is converted to a set?

Example:
data = [1,2,3,4,5,5,5,5,6]

# this turns list to set and overwrites the list
data = set(data)

print data 
# output will be (1,2,3,4,5,6)

3 Answers 3

12

Converting a list to a set requires that every item in the list be visited once, O(n). Inserting an element into a set is O(1), so the overall time complexity would be O(n).

Space required for the new set is less than or equal to the length of the list, so that is also O(n).

Here's a good reference for Python data structures.

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

1 Comment

I believe the set while inserting, sorts the elements as well. That would make the time complexity O(n.logn).
1

You have to iterate through the entire list, which is O(n) time, and then insert each into a set, which is O(1) time. So the overall time complexity is O(n), where n is the length of the list.

No other space other than the set being created or the list being used is needed.

Comments

0

As others have stated regarding the runtime, the set creation time is O(N) for the entire list, and set existence check is O(1) for each item.

But their comments on memory usage being the same between lists and sets are incorrect.

In python, sets can use 3x to 10x more memory than lists. Set memory usage growth still O(N), but it's always at least 3x more than lists. Maybe because of needing to keep in memory all those hashes.

related: https://stackoverflow.com/a/54891295/1163355

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.