Skip to content

S2Q1 · Add Two to Alternate Elements

⚡ Quick Reference

Function: add_two_to_alternate_elements(t: tuple) -> tuple

Core idea: Use enumerate to get each index, add 2 when the index is even, wrap back in tuple().

def add_two_to_alternate_elements(t):
    return tuple(x + 2 if i % 2 == 0 else x for i, x in enumerate(t))

Key rules: - Even indices (0, 2, 4, ...): add 2 - Odd indices: leave unchanged - Return a tuple, not a list


Problem Statement

Problem

Write a function add_two_to_alternate_elements(t) that takes a tuple of integers and returns a new tuple where 2 is added to every element at an even index. Elements at odd indices are unchanged. The tuple always has at least one element.

Examples:

Call
add_two_to_alternate_elements((1, 2, 3, 4, 5))
Output
(3, 2, 5, 4, 7)
Call
add_two_to_alternate_elements((10, 20))
Output
(12, 20)

Understanding the problem

Trace (1, 2, 3, 4, 5):

Index Value Even index? Result
0 1 ✅ 1 + 2 = 3
1 2 ✗ 2
2 3 ✅ 3 + 2 = 5
3 4 ✗ 4
4 5 ✅ 5 + 2 = 7

Output: (3, 2, 5, 4, 7)

enumerate() gives both index and value together

Without enumerate, you'd need a separate counter or use range(len(t)) to track the index. enumerate(t) yields (index, value) pairs directly, making i % 2 == 0 the natural parity check.


Solution approaches

def add_two_to_alternate_elements(t: tuple) -> tuple:
    result = []
    for i, x in enumerate(t):
        if i % 2 == 0:       # even index: add 2
            result.append(x + 2)
        else:                # odd index: keep as-is
            result.append(x)
    return tuple(result)
def add_two_to_alternate_elements(t: tuple) -> tuple:
    return tuple(x + 2 if i % 2 == 0 else x for i, x in enumerate(t))
add_two_to_alternate_elements = lambda t: tuple(
    x + 2 if i % 2 == 0 else x for i, x in enumerate(t)
)

Key takeaways

01

enumerate() for index-aware iteration

for i, x in enumerate(t) gives the index i and value x simultaneously. It's the idiomatic Python alternative to for i in range(len(t)) followed by t[i].

02

Generator expression inside tuple()

tuple(expr for ...) builds a tuple directly from a generator -- no intermediate list needed. The parentheses of tuple() wrap the generator, so no extra brackets are required.

03

Tuples are immutable -- always return a new one

You cannot modify a tuple in place. The correct approach is to build a new sequence (list or generator) with the changes applied, then wrap it in tuple() to return the right type.