8

Is it possible? Obviously x[1:-1].sort() doesn't work because the slice is a copy.

Current workaround:

>>> x = [4, 3, 1, 2, 5]
>>> s = slice(1, -1)
>>> x[s] = sorted(x[s])
>>> x
[4, 1, 2, 3, 5]

Can I somehow get a view on a python list?

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    Related: [Can I create a “view” on a Python list?](http://stackoverflow.com/questions/3485475/can-i-create-a-view-on-a-python-list) – Ashwini Chaudhary Jan 27 '14 at 12:44
  • See http://www.shaunlippy.org/blog/?p=77 – Mihai8 Jan 27 '14 at 13:00
  • There is now view for a list in python, afaik, as it exists for dict's (dict.viewkey etc.). I don't see any usecases for views on a list, so what do you mean by view & what should it provide? (```b=x``` would be some sort of a view, although it's quite useless). – dorvak Jan 27 '14 at 13:12
  • `x[1:-1] = sorted(x[1:-1])` is quite neat in my opinion. Why do you dislike it? – ejrb Jan 27 '14 at 13:36
  • I guess you're right. Taking the slice is O(n) but it's irrelevant because the sort is O(n*log(n)) anyway – wim Jan 27 '14 at 13:48

1 Answers1

5

If numpy is an option:

>>> x = np.array([1, 8, 90, 30, 5])
>>> x[2:].sort()
>>> x
array([ 1,  8,  5, 30, 90])

numpy array slices are always views of the original array.

Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31