Reference library

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

2 matches
Lists & loops easy

How to Rotate a List in Python

Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.

list rotation slicing
Python
def rotate_list_right(lst, k):
    if not lst:
        return lst
    k = k % len(lst)
    return lst[-k:] + lst[:-k] if k != 0 else lst


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7]
    for k in [0, 1, 3, 8, 20]:
        print(f"k={k}: {rotate_list_right(sample, k)}")
15 0 Open
Lists & loops easy

Rotate List Left by k Positions in Python

Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.

list rotation slicing
Python
def rotate_left(lst, k):
    if not lst:
        return []
    k = k % len(lst)
    return lst[k:] + lst[:k]

if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    k = 2
    result = rotate_left(my_list, k)
    print(f"Original: {my_list}")
    print(f"After rotating left by {k}: {result}")
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Lists & loops — Python code examples

What you will find here

This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.