arrays - How to create a new data object in memory, rather than pointing to one? (in Python 3) -


as illustration of question, want swap 2 elements in array:

# array integer integer -> array # want swap values @ locations i1 , i2.  # want return array values swapped. def swap(a, i1, i2):     newa =     newa[i1] = a[i2]     newa[i2] = a[i1]     return newa 

run code, , array returned 1 value changed:

> testarray = [1, 2, 3, 4] > swap(testarray, 0, 1) [2, 2, 3, 4] 

also, if check testarray (i want still [1, 2, 3, 4]):

> testarray [2, 2, 3, 4] 

so questions are:

  1. i guess newa = uses pointer a. i'm used programming in style return new data structure each time. i'd create whole new array, newa, has same values a. can let garbage collection take care of newa later. can in python?

  2. what newa = doing?

  3. why create new variable (like newa) point old 1 (a)? why wouldn't mutate directly?

  4. and why syntax behave differently atomic data?

i.e.

a = 1 b = # same syntax doesn't seem pointer. b = 2 > 1 

  1. how create new list?

some ways , timings large , small lists:

>>> way in 'a[:]', 'list(a)', 'a.copy()':     print(way, timeit(way, 'a = list(range(100000))', number=10000))  a[:] 7.3193273699369 list(a) 7.248674272188737 a.copy() 7.366528860679182  >>> way in 'a[:]', 'list(a)', 'a.copy()':     print(way, timeit(way, 'a = list(range(10))', number=10000000))  a[:] 4.324301856050852 list(a) 7.022488782549999 a.copy() 4.61609732160332 

  1. what newa = doing?

makes variable newa reference same object a references.


  1. why create new variable (like newa) point old 1 (a)? why wouldn't mutate directly?

just example:

if <something>:     =     ... else:     = b     ... <modify now> 

  1. and why syntax behave differently atomic data?

it doesn't. make new variable reference same object, ints. don't notice it, because ints can't changed. can see testing is:

>>> = 1234 >>> b = >>> b true               <== see? >>> b = 1234 >>> b false              <== , it's different 1234 object 

Comments