- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to 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]
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))
[2, 6, 3, 9, 6, 4, 6, 7, 5]
- Python List Comprehension and Slicing?
- Program to reverse a linked list in Python
- Python program to Reverse a range in list
- Alternate range slicing in list (Python)
- Program to reverse linked list by groups of size k in Python
- Python program to sort and reverse a given list
- Reverse Linked List in Python
- Program to reverse inner nodes of a linked list in python
- Golang Program to reverse a given linked list.
- C Program for Reverse a linked list
- Python program to right rotate a list by n
- Python Program to Reverse only First N Elements of a Linked List
- How to reverse the objects in a list in Python?
- Python Program to Display the Nodes of a Linked List in Reverse using Recursion
- How to Reverse a linked list in android?