1

Take list foo

foo = [5, 6, 7, 8, 9, 10, 11, 12]

How can I reverse only the elements of indices x to y within the list?
For example:

x = 1
y = 5
# reverse foo[x:y]
foo = [5, 9, 8, 7, 6, 10, 11, 12]
chambln
  • 363
  • 1
  • 2
  • 9

3 Answers3

4

Python allows you to assign to slices

Slicings may be used as expressions or as targets in assignment or del statements

thus it's possible to do everything on one line:

foo[x:y] = foo[y-1:x-1:-1]

Note thatfoo[y-1:x-1:-1] has the same meaning as foo[x:y][::-1].

vaultah
  • 44,105
  • 12
  • 114
  • 143
2

It's as simple as:

foo[x:y] = foo[y - 1:x - 1:-1]

For example:

>>> foo = [5, 6, 7, 8, 9, 10, 11, 12]
>>> foo[1:5] = foo[4:0:-1]
>>> foo
[5, 9, 8, 7, 6, 10, 11, 12]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1
def reverse(l, x, y):
    l[x:y+1] = l[y:x-1:-1]

foo = [5, 6, 7, 8, 9, 10, 11, 12]
x = 1
y = 4

reverse(foo, x, y)
print(foo) # [5, 9, 8, 7, 6, 10, 11, 12]
maahl
  • 547
  • 3
  • 17