Home > python > Reverse a part (slice) of a list

Reverse a part (slice) of a list

Problem
You have a list and you want to reverse a part (slice) of it.

Solution
Let our list be [1,2,9,6,5] and say we want to reverse its end from element 9, i.e. we want to get [1,2,5,6,9].

a = [1,2,9,6,5]
i = 2    # reverse from this index position
j = 4    # reverse until this index position (included)
a[i:j+1] = reversed(a[i:j+1])
print a    # [1, 2, 5, 6, 9]
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: