To rotate elements in a list in Python, you can use list slicing and concatenation.
In this example,
numbers
with integer values.numbers = [1, 2, 3, 4, 5]
distance = 2
rotated_numbers = numbers[-distance:] + numbers[:-distance]
print('Rotated list:', rotated_numbers)
Rotated list: [4, 5, 1, 2, 3]
In this example,
words
with string values.words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
distance = 3
rotated_words = words[-distance:] + words[:-distance]
print('Rotated list:', rotated_words)
Rotated list: ['cherry', 'date', 'elderberry', 'apple', 'banana']
In this tutorial, we learned How to Rotate Elements in a List in Python language with well detailed examples.