Program to reverse a list by list slicing in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of n elements called nums. We have to reverse this list by list slicing operations.

So, if the input is like nums = [5,7,6,4,6,9,3,6,2], then the output will be [2, 6, 3, 9, 6, 4, 6, 7, 5]

To solve this, we will follow these steps −

  • list slicing takes at most three parameters separated by colon. First one is start, second one is end and third one is step
  • here as we start from 0 we do not pass first parameter, as we end at n, we also not providing second argument, but as we need reversal we need the step parameter -1. So it will decrease one by one. So slicing syntax will be like [::-1]

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   return nums[::-1]
nums = [5,7,6,4,6,9,3,6,2]
print(solve(nums))

Input

[5,7,6,4,6,9,3,6,2]

Output

[2, 6, 3, 9, 6, 4, 6, 7, 5]
raja
Published on 12-Oct-2021 07:17:01
Advertisements