
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse a List by List Slicing in Python
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]
Advertisements