Python: create sublist without copying
Question: I have a question about how to create a sublist (I hope this is the right term
to use) from a given list without copying.

It seems that slicing can create sublists, but does it with copying. Here is
an example.

    
    
    In [1]: a = [1,2,3]
    
    In [2]: id(a)
    Out[2]: 4354651128
    
    In [3]: b = a[0:2]
    
    In [4]: b
    Out[4]: [1, 2]
    
    In [5]: id(b)
    Out[5]: 4354621312
    
    In [6]: id(a[0:2])
    Out[6]: 4354620880
    

See here the id of b and a[0:2] are different, although their values are the
same. To double check, change the value in a, the value in b does not change.

    
    
    In [7]: a[1] = 4
    
    In [8]: a
    Out[8]: [1, 4, 3]
    
    In [9]: b
    Out[9]: [1, 2]
    

So to get back to my question, how can I create sublists but without copying?
I mean, when value of a[1] is set to 4, b will be [1, 4].

I searched around and did not find much help (maybe I am not using the right
keywords). Thank you!

* * *

Edits:

Thank you all for your comments and answers! Here is what I have learned.

  * There is no built-in way in Python to create a view of a list (or to create a sublist without copying).
  * The easiest way to do this is to use the numpy array.
  * Although numpy array has limitations on data type compared with list, it does serve my purpose (to implement quicksort with no extra memory)

Here is the same process with numpy array.

    
    
    In [1]: import numpy as np
    
    In [2]: a = np.arange(1,4)
    
    In [3]: a
    Out[3]: array([1, 2, 3])
    
    In [4]: b = a[0:2]
    
    In [5]: b
    Out[5]: array([1, 2])
    
    In [6]: id(b)
    Out[6]: 4361253952
    
    In [7]: id(a[0:2])
    Out[7]: 4361254032
    
    In [8]: a[1] = 4
    
    In [9]: a
    Out[9]: array([1, 4, 3])
    
    In [10]: b
    Out[10]: array([1, 4])
    


Answer: `numpy`'s array objects support this notion of creating interdependent sub-
lists, by having slicing return `views` rather than copies of the data.

Altering the original `numpy` array will alter the views created from the
array, and changes to any of the views will also be reflected in the original
array. Especially for large data sets, views are a great way of cutting data
in different ways, while saving on memory.

    
    
    >>> import numpy as np
    >>> array1 = np.array([1, 2, 3, 4])
    >>> view1 = array1[1:]
    >>> view1
    array([2, 3, 4])
    >>> view1[1] = 5
    >>> view1
    array([2, 5, 4])
    >>> array1
    array([1, 2, 5, 4]) # Notice that the change to view1 has been reflected in array1
    

For further reference, see the [`numpy` documentation on
views](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html)
as well as [this SO post](http://stackoverflow.com/questions/4370745/view-
onto-a-numpy-array).

