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]
1
  • Slice it out, reverse it, and concatenate everything back together. Commented Mar 29, 2015 at 14:41

3 Answers 3

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].

Sign up to request clarification or add additional context in comments.

1 Comment

it doesn't seems to work when x is pointing the index 0
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]

1 Comment

can I get that in terms of x and y?
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]

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.