Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 768
db_ Avatar asked Mar 15 '23 05:03

db_


1 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 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]
like image 174
Padraic Cunningham Avatar answered Mar 17 '23 19:03

Padraic Cunningham