Reorder a List by Odd Even Indices in Python
Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.
Python code
16 linesdef reorder_by_odd_even(items):
"""Reorders a list so that elements at odd indices come first,
followed by elements at even indices (1-based).
Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
"""
odds = [items[i] for i in range(1, len(items), 2)]
evens = [items[i] for i in range(0, len(items), 2)]
return odds + evens
if __name__ == "__main__":
original = [0, 1, 2, 3, 4, 5, 6]
reordered = reorder_by_odd_even(original)
print(f"Original: {original}")
print(f"Reordered (odd indices first, then even): {reordered}")
Output
Original: [0, 1, 2, 3, 4, 5, 6]
Reordered (odd indices first, then even): [1, 3, 5, 0, 2, 4, 6]
How it works
This function uses two list comprehensions with range(start, len(items), 2) to pick every other element. The first comprehension starts at index 1, collecting all 1-based odd positions; the second starts at index 0, gathering even positions. Concatenating these sublists produces the desired pattern. This approach runs in O(n) time and uses O(n) extra space, making it efficient for most real-world list sizes.
Common mistakes
- Confusing 0-based vs 1-based indexing — the pattern expects 1,3,5 first, not 0,2,4.
- Using `items[1::2]` and `items[::2]` without realizing slice order still needs odds before evens.
- Forgetting that empty lists or single-element lists return a different order than expected.
Variations
- Use slicing: `items[1::2] + items[::2]` for a more concise one-liner.
- In-place reorder using a loop and swapping elements to avoid extra memory.
Real-world use cases
- Rearranging display order in a two-column card layout so natural reading order maps correctly.
- Merging two interleaved data streams (e.g., alternate sensor readings) back into grouped blocks.
- Preprocessing audio or signal samples where alternating channels need regrouping before analysis.
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.