-1

I have the next list:

abclist = ['a', 'b', 'c', 'd', 'e']

With the above list I how to create the next one?

Reversed_part = ['c', 'b', 'a', 'd', 'e']

Only the first 3 items are reversed and the last two stay in the same order.

jpp
  • 159,742
  • 34
  • 281
  • 339
Inti
  • 69
  • 4
  • Select the part that you want to reverse (by slicing), reverse it, then combine with the other unreversed parts. – DYZ Mar 17 '18 at 03:53
  • 1
    `rev = abclist[3::-1] + abclist[3:]` – Stephen Rauch Mar 17 '18 at 03:54
  • 1
    Possible duplicate of [How do I reverse a part (slice) of a list in Python?](https://stackoverflow.com/questions/4647368/how-do-i-reverse-a-part-slice-of-a-list-in-python). Also [this](https://stackoverflow.com/questions/22257249/how-do-i-reverse-a-sublist-in-a-list-in-place) and possibly [this](https://stackoverflow.com/questions/43506123/slicing-to-reverse-part-of-a-list-in-python). – pault Mar 17 '18 at 04:29

3 Answers3

2

This is one way.

lst = ['a', 'b', 'c', 'd', 'e']

def partial_reverse(lst, start, end):

    """Indexing (start/end) inputs begins at 0 and are inclusive."""

    return lst[:start] + lst[start:end+1][::-1] + lst[end+1:]

partial_reverse(lst, 0, 2)  # ['c', 'b', 'a', 'd', 'e']
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can do it using a combination of reversed method & string slicing

Ex:

abclist = ['a', 'b', 'c', 'd', 'e']
print(list(reversed(abclist[:3]))+abclist[-2:])

Output:

['c', 'b', 'a', 'd', 'e']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0
abclist = ['a', 'b', 'c', 'd', 'e']
quantityToReverse = 3
remainder = len(abclist) - quantityToReverse
reverseArray = list(reversed(abclist[:quantityToReverse]))+abclist[-remainder:]

print(reverseArray)
JohanaAnez
  • 31
  • 5
  • Welcome to SO. Answers usually benefit from an explanation, what the code does. This helps the OP to understand the answer and attracts more upvotes. – Mr. T Mar 17 '18 at 08:02