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:
Example

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

[5, 4, 3, 2, 1, 8, 7, 6]


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

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.