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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

10 lines
Python 3.9+
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)

Output

stdout
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)]

How it works

The list comprehension iterates over indices from 0 to len(lst)-1. For each i, it builds a tuple (lst[i], lst[(i+1) % len(lst)]). The modulo operator wraps the last index back to 0, creating the cyclic pairing. For an empty list, the function returns an empty list to avoid division by zero in the modulo operation.

Common mistakes

  • Forgetting to handle the empty list case, leading to a ZeroDivisionError
  • Using a non-wrapping index like i+1 without modulo, which skips the last pair
  • Assuming the input is always non-empty without validation

Variations

  1. Using zip(lst, lst[1:] + lst[:1]) for a more functional approach
  2. Using a generator expression for memory efficiency on large lists

Real-world use cases

  • Rotating signals in a round-robin scheduler to assign tasks sequentially across workers.
  • Cyclically linking nodes in a circular linked list implementation for game or simulation loops.
  • Pairing adjacent frames in a video processing pipeline where the last frame wraps to the first for smooth transitions.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.