Search code examples
pythonspace-complexity

Does updating the list take extra space?


I have an array or list, Now I want to make some changes in the array and put in back to the arr variable/list. Am I using extra space? or it is the same variable gets updated again?

arr = [1,2,3,4]
print arr[2:] + arr[:2] # Is is using extra space
#or
arr = arr[2:] + arr[:2] # Is is using extra space
#or
arr = [1,2,3,4]
arr = arr # are not they both same? LHS arr is different from RHS arr

Solution

  • when assigning like this:

    arr = arr[2:] + arr[:2]
    

    you're creating a new reference of arr, and the old one is destroyed. Means allocation/deletion.

    You should do slice assignment:

    arr[:] = arr[2:] + arr[:2]
    

    arr keeps the same reference, and if the size doesn't change, no memory allocaton occurs for arr (but the right hand side sum & slicing still needs allocation)

    Demo:

    arr = [1,2,3,4]
    old_arr = arr
    arr = arr[2:] + arr[:2]
    print(old_arr is arr)
    

    result: False

    arr = [1,2,3,4]
    old_arr = arr
    arr[:] = arr[2:] + arr[:2]
    print(old_arr is arr)
    

    result: True