Alex Rivera | Logout

Can I create a "view" on a Python list?

Asked 2010-08-14T23:05:46.043
67

I have a large list l. I want to create a view from element 4 to 6. I can do it with sequence slice.

>>> l = range(10)
>>> lv = l[3:6]
>>> lv
[3, 4, 5]

However lv is a copy of a slice of l. If I change the underlying list, lv does not reflect the change.

>>> l[4] = -1
>>> lv
[3, 4, 5]

Vice versa I want modification on lv reflect in l as well. Other than that the list size are not going to be changed.

I'm not looking forward to build a big class to do this. I'm just hoping other Python gurus may know some hidden language trick. Ideally I hope it can be like pointer arithmetic in C:

int lv[] = l + 3;
Edit
Report

1 Answer

1

Edit: The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). - so no, sadly.

I think buffer type is what you are looking for.

Pasting example from linked page:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05' 
answered 2010-08-15T00:32:44.467

Your Answer