Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements.
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 10 Output: [8, 7, 6, 5, 4, 3, 2, 1]
We have existing solution for this problem please refer Reverse an array in groups of given size link. We can solve this problem quickly in Python using list slicing and reversed() function.Below example will give you better understanding of approach.
Example:

# function to Reverse an array in groups of given size def reverseGroup(input,k): # set starting index at 0 start = 0 # run a while loop len(input)/k times # because there will be len(input)/k number # of groups of size k result = [] while (start<len(input)): # if length of group is less than k # that means we are left with only last # group reverse remaining elements if len(input[start:])<k: result = result + list(reversed(input[start:])) break # select current group of size of k # reverse it and concatenate result = result + list(reversed(input[start:start + k])) start = start + k print(result) # Driver program if __name__ == "__main__": input = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 reverseGroup(input,k) |
chevron_right
filter_none
Output:
[5, 4, 3, 2, 1, 8, 7, 6]
Recommended Posts:
- Python | Reverse Slicing of given string
- Program to cyclically rotate an array by one in Python | List Slicing
- Python | Variable list slicing
- Python | Custom slicing in List
- Python List Comprehension and Slicing
- Interesting facts about strings in Python | Set 2 (Slicing)
- Python | Get the substring from given string using list slicing
- Python | Alternate range slicing in list
- Python Slicing | Extract ‘k’ bits from a given position
- Python | Reverse a numpy array
- Basic Slicing and Advanced Indexing in NumPy Python
- Python | Reverse an array upto a given position
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Summation of Non-Zero groups
- String slicing in Python to rotate a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



