Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11968

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

Upvotes: 0

Views: 203

Answers (2)

Conic
Conic

Reputation: 1208

<1,2,3,4> are stored somewhere in memory. arr has references to <1,2,3,4> and arr[2:] has references to the same <3,4> that arr has references to.

For a list of numbers, you're using extra space for those references but not the numbers themselves.

For a list of high profile objects this actually becomes a more memory efficient means to dealing with it.

I suggest reading through this:
http://foobarnbaz.com/2012/07/08/understanding-python-variables/

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140276

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

Upvotes: 2

Related Questions