← Previous Module 4: Lists & Tuples Next →
Statement
Solution

Python Exercise 4.3: List Rotation

Write a program that takes a list and "rotates" it to the right by k steps.

Example: [1, 2, 3, 4, 5] rotated by 2 becomes [4, 5, 1, 2, 3].

Your program should:

  • Start with a fixed list (e.g., [1, 2, 3, 4, 5]).
  • Ask the user for the number of steps k (integer).
  • Create a new list by slicing the original list.
  • The last k elements move to the front.
  • The remaining elements follow after them.
  • Print the rotated list.

Sample Interaction:

Input
Output
2
Original: [1, 2, 3, 4, 5] Enter rotation steps (k): 2 Rotated: [4, 5, 1, 2, 3]

Solution

Python's list slicing makes this easy. We take the last k items and append the rest of the list to them.

# 1. Define the list my_list = [1, 2, 3, 4, 5] print(f"Original: {my_list}") # 2. Get rotation steps k k = int(input("Enter rotation steps (k): ")) # 3. Handle cases where k > list length # The modulo operator ensures k is within bounds k = k % len(my_list) # 4. Perform rotation using slicing # last k elements + elements from start up to end-k rotated_list = my_list[-k:] + my_list[:-k] # 5. Print result print(f"Rotated: {rotated_list}")

Key Concepts:

  • my_list[-k:] gets the last k elements.
  • my_list[:-k] gets everything EXCEPT the last k elements.
  • k % len(my_list) handles cases where k is larger than the list size (e.g., rotating a list of 5 items by 7 steps is the same as rotating by 2).
Python 3
Test Console
Run code to see output...

Scroll to Top