pythonlistpointer-aliasing

Create alias of part of a list in python


Is there a way to get an alias for a part of a list in python?

Specifically, I want the equivalent of this to happen:

>>> l=[1,2,3,4,5]
>>> a=l
>>> l[0]=10
>>> a
[10, 2, 3, 4, 5]

But what I get is this:

>>> l=[1,2,3,4,5]
>>> a=l[0:2]
>>> l[0]=10
>>> a
[1, 2]

Solution

  • If numpy is an option:

    import  numpy as np
    
    l = np.array(l)
    
    a = l[:2]
    
    l[0] = 10
    
    print(l)
    print(a)
    

    Output:

    [10  2  3  4  5]
    [10  2]
    

    slicing with basic indexing returns a view object with numpy so any change are reflected in the view object

    Or use a memoryview with an array.array:

    from array import array
    
    l = memoryview(array("l", [1, 2, 3, 4,5]))
    
    a = l[:2]
    
    l[0]= 10
    print(l.tolist())
    
    print(a.tolist())
    

    Output:

    [10, 2, 3, 4, 5]
    [10, 2]