Home› Python Programming Language› / Programs / Slice list into 3 equal chunks and reverse each chunk
🚀 Programming Example

Slice list into 3 equal chunks and reverse each chunk

1,325 Views
Beginner
Code Snippet
Write a python program to slice list into 3 equal chunks and reverse each chunk

📌 Information & Algorithm

  • Divide the length of a list by 3 to get the each chunk size
  • Run loop three times and use the slice() function to get the chunk and reverse it

Given Input:

sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]

Expected Output:

Chunk  1 [11, 45, 8]
After reversing it  [8, 45, 11]
Chunk  2 [23, 14, 12]
After reversing it  [12, 14, 23]
Chunk  3 [78, 45, 89]
After reversing it  [89, 45, 78]

💻 Program Code

sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]
print("Original list ", sample_list)

length = len(sample_list)
chunk_size = int(length / 3)
start = 0
end = chunk_size

# run loop 3 times
for i in range(3):
    # get indexes
    indexes = slice(start, end)
    
    # get chunk
    list_chunk = sample_list[indexes]
    print("Chunk ", i, list_chunk)
    
    # reverse chunk
    print("After reversing it ", list(reversed(list_chunk)))

    start = end
    end += chunk_size

🖥 Program Output

                                Original list  [11, 45, 8, 23, 14, 12, 78, 45, 89]
Chunk  0 [11, 45, 8]
After reversing it  [8, 45, 11]
Chunk  1 [23, 14, 12]
After reversing it  [12, 14, 23]
Chunk  2 [78, 45, 89]
After reversing it  [89, 45, 78]
                            

📘 Explanation

  • Get the length of a list using a len() function
  • Divide the length by 3 to get the chunk size
  • Run loop three times
  • In each iteration, get a chunk using a slice(start, end, step) function and reverse it using the reversed() function
  • In each iteration, start and end value will change
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.