-2

I want to do something like this:

myList[n]. Shift myList[k:l] to the left by s.

Example: Let n be 5, s = 1 and k and l be the 3rd and 4th element in the list.

Before:

[a,a,b,b,a]

After:

[a,b,b,a,a]

To be clear: I don't want to loose 'b' items in my list, 'a' can be overwritten.

What would be the most time and space efficient way to achieve this in Python?

Edit: NO ROTATION!

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • Your example is not very clear. You could just as well have used "before: `[a,a,a,a,a]`, after: `[a,a,a,a,a]`"... – tobias_k Mar 24 '14 at 13:02
  • The problem with your example is that it is not clear which a/b in 'before' maps to which a/b in 'after'. The same 'after' result could have been achieved with a shift, a rotation, or even by mirroring the list. My example was not meant to be a better example, but for exemplifying the problem with your example. – tobias_k Mar 24 '14 at 13:22

1 Answers1

2

Using list slice:

>>> lst = [1, 2, 3, 4, 5]
>>> s, k, l = 1, 2, 4 # 4 = 3 + 1
>>> x = lst[k:l]
>>> del lst[k:l]
>>> lst[k-s:k-s] = x
>>> lst
[1, 3, 4, 2, 5]
falsetru
  • 357,413
  • 63
  • 732
  • 636