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]
db_
  • 103
  • 1
  • 2
  • 7
  • Slicing creates a new `list`. If you had two `list`s of different sizes, how could they be the same list, i.e., have the same address? – TigerhawkT3 Aug 03 '15 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](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Aug 03 '15 at 22:01

3 Answers3

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]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
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.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
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])
Anonymous
  • 11,740
  • 3
  • 40
  • 50