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.
Python code
10 linesdef 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
[(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
- Using zip(lst, lst[1:] + lst[:1]) for a more functional approach
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.