Create an alias of part of a list in python

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

In particular, I want this to happen:

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

But I get the following:

 >>> l=[1,2,3,4,5] >>> a=l[0:2] >>> l[0]=10 >>> a [1, 2] 
+4
source share
3 answers

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 is reflected in the view object

Or use memoryview with 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] 
+6
source

You can embed each element in your own mutable data structure (e.g. list ).

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

However, I recommend coming up with a solution to your original problem (whatever it was) that does not create your own problems.

0
source

What you are looking for is a representation of the source list, so any changes are reflected in the source list. This can be done with an array in the numpy package:

 >>> import numpy >>> x = numpy.array([1, 2, 3]) >>> y = x[2:] >>> y[0] = 999 >>> x array([ 1, 2, 999]) 
0
source

All Articles