Reference library

Algorithms & data structures

Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.

2 matches
Algorithms & data structures easy

How to Rotate an Array by k Steps in Python

This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.

array rotation algorithms
Python
def rotate_array(nums, k):
    if not nums:
        return []
    n = len(nums)
    k = k % n
    return nums[-k:] + nums[:-k] if k else nums[:]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 2
    result = rotate_array(arr, k)
    print(f"Original: {arr}")
    print(f"Rotated by {k}: {result}")
13 0 Open
Algorithms & data structures easy

Pair Elements with Next Cyclic Neighbor in Python

Create tuples pairing every element with its next element, wrapping around to the first element for the last one.

pairs cyclic list
Python
def cyclic_pairs(lst):
    if not lst:
        return []
    return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5]
    result = cyclic_pairs(sample)
    print(result)
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Algorithms & data structures — Python code examples

What you will find here

This page collects algorithms & data structures 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.