4

Supoose I have a python list a = [0,1,2,3,4,5]. now I neeed to make a list b such that b should contain elements [1,2,3], but as a reference to a. By this I mean that if I change a[1] = 3 then b[0] should alsoe be 3. How shall I achieve this?

from what I know, with b = a I can have copy by reference, but only possible with full list, and if I do b = a[1:4], then its a seperate copy.

Amrith Krishna
  • 2,768
  • 3
  • 31
  • 65
  • Using a NumPy array you can do this easily, as slicing returns a view there instead of shallow copy. There's [`memoryview`](https://docs.python.org/2/library/stdtypes.html#memoryview) type in Python, but it is only limited to objects that support buffer. – Ashwini Chaudhary Nov 23 '14 at 15:28
  • The list contains custom made objects. so numpy wont work – Amrith Krishna Nov 23 '14 at 15:32
  • 1
    That doesn't matter, slicing will still work. NumPy will simply use dtype=object if you throw in random objects. – Ashwini Chaudhary Nov 23 '14 at 15:40

0 Answers0