Sunday, February 15, 2015

List assignment in python

Normally assignment with = does not make a copy of the list. In fact assignment makes two variables to point to same location in mamory.

colors = ['red', 'blue', 'green']
  print colors[0]    ## red
  print colors[2]    ## green
  print len(colors)  ## 3
list of strings 'red' 'blue 'green'
b = colors   ## Does not copy the list
both colors and b point to the one list

---------------------------------------------------
so to copy the list you have different options :

you can slice it :
new_list = old_list[:]
OR

use generic copy.copy:
import copy
new_list = copy.copy(old_list)
OR

use built in function list():
new_list = list(old_list)

OR if the list contains object use generic copy.deepcopy()
import copy
new_list = copy.deepcopy(old_list)

Obviously the slowest and most memory-needing method, but sometimes unavoidable.

!!!! NOTE :
But be aware that copy.copy(), list[:] and list(list), unlike copy.deepcopy() and the python version don't copy any lists, dictionaries and class instances in the list, so if the originals change, they will change in the copied list too and vice versa.

No comments:

Post a Comment