Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running time for converting list to set in Python

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)
like image 340
Sriram Avatar asked Sep 03 '26 10:09

Sriram


1 Answers

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.

like image 113
mhawke Avatar answered Sep 05 '26 00:09

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!