Search code examples
pythonmemorycomplexity-theory

Memory complexity of reassign in python


I'm wondering what is the memory complexity of reassigning a linear variable in python to a new linear type variable. For instance, consider a function with one list parameter, which converts it to set.

def func(list_var):
    list_var = set(list_var)
    return list_var

Is it O(n) memory complexity or O(1)?


Solution

  • The assignment itself isn't necessary; the following has exactly the same semantics from the view of the caller:

    def func(list_var):
        return set(list_var)
    

    The important part is the call to set, which has to allocate a data structure with n new references, one per element in list_var, so the space complexity is O(n).