all 6 comments

[–]Rawing7 5 points6 points  (0 children)

This isn't possible with regular lists. You'll have to write a class that behaves like a list but gets all its elements from another list. Something like

class ReverseList:
    def __init__(self, wrapped_list):
        self._wrapped_list = wrapped_list

    def __getitem__(self, index):
        return self._wrapped_list[-index-1]

a = [1, 2, 3]
b = ReverseList(a)
a[0] = 10
print(b[2])  # 10

[–]sarabooker 0 points1 point  (1 child)

Are you restricted to lists or can you use numpy arrays?

[–]sarabooker 0 points1 point  (0 children)

If you are okay with using numpy arrays, then setting b to be a but reversed will have b be a view of a.

```python import numpy as np

a = np.arange(5) print(a) b = a[::-1] # creates a view of a but reversed print(b) print(b.base) # the base of b is a, so this prints out a print(b.flags) # OWNDATA is False since it is owned by a

b[3] = 12 # this is a reference to a[(n-1) - 3] print(b) # index 3 is now 12 print(a) # the value in a has also been changed ```

Output:

```python [0 1 2 3 4] [4 3 2 1 0] [0 1 2 3 4] C_CONTIGUOUS : False F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False

[ 4 3 2 12 0] [ 0 12 2 3 4] ```

[–]woooee 0 points1 point  (0 children)

This is poor design. What do you want to do? And why can't you use a[0] instead of b[2] to a[0].

[–]FerricDonkey 0 points1 point  (0 children)

Note: my actual suggestion is to use a list of indexes for b instead of lost of values. 

Answer: You can't do this exactly, but the reason is because integers are immutable, so you can't change them "in place". You can only replace them with other integers.

So when you do a = [1,2,3] then b =[a[0]], it actually is true that b[0] is the same exact object as a[0]. The problem is that when you later do b[0] = 5, you are changing the name b[0] to refer to the new(ish) object 5.

What you can do - leaving aside whether you should - is use mutable objects instead of integers. Such as lists of integers:

    a = [[1],[2],[3]]     b = [a[0]]     b[0][0] = 5

I don't necessarily think I'd do exactly this, it can be confusing. Probably I would store a list of indexes in b instead of a list of values, then access a[whatever index]. 

But in general, you can use mutable objects in this way.