Choice of List & Array in Python
2013-02-24
list is able to store heterogeneous and arbitrary data, but takes a lot more spaces than C arrays. Array in python is the wrapper of C array structure, which takes up a continuous block of memory and only stores the same type of data.
You should use arrays if you know that everything in the "list" will be of the same type and you want to store the data more compactly. Otherwise, list is more flexible.
Because lists are mutable, when you change that list, all of the references get "automatically" updated. This feature of multiple references to the same list can lead to side effects.
Note that operations that modify the list will modify it in place. This means that if you have multiple variables that point to the same list, all variables will be updated at the same time. # modify both lists # modify L only
L = []
M = L</p>
L.append(obj)
</code>
To create a separate list, you can use slicing or the list function to quickly create a copy:
L = []
M = L[:] # create a copy</p>
L.append(obj)
</code>
References:
http://stackoverflow.com/questions/9405322/python-array-v-list
http://effbot.org/zone/python-list.htm