4

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]
2
  • Slicing creates a new list. If you had two lists of different sizes, how could they be the same list, i.e., have the same address? Commented Aug 3, 2015 at 21:59
  • I guess you could embed each element into its own list, but that would be so hacky. You probably have an XY Problem. Commented Aug 3, 2015 at 22:01

3 Answers 3

8

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]
Sign up to request clarification or add additional context in comments.

Comments

0

You could embed each element into its own mutable data structure (like a 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 trying to come up with a solution to your original issue (whatever that was) that doesn't create issues of its own.

Comments

0

What you're looking for is a view of the original list, so that any modifications are reflected in the original list. This is doable with the array in the numpy package:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.