Skip to content

S2Q1 · Uppercase Even Index Words

⚡ Quick Reference

Function: alternate_upper(sentence: str) -> list

Core idea: split into words, uppercase those at even indices (0, 2, 4, …), leave odd indices unchanged.

def alternate_upper(sentence: str) -> list:
    words = sentence.split()
    return [w.upper() if i % 2 == 0 else w for i, w in enumerate(words)]

Key rules: - 0-based indexing -index 0 is the first word (uppercase) - Even index → w.upper(), odd index → keep as-is - Return a list, not a string


Problem Statement

Problem

Write a function alternate_upper(sentence) that returns a list of words where words at even indices (0, 2, 4, …) are uppercased and words at odd indices remain unchanged.

Examples:

Input
"india is my country"
Output
['INDIA', 'is', 'MY', 'country']
Input
"this is a test case"
Output
['THIS', 'is', 'A', 'test', 'CASE']

Tracing the example

"india is my country"["india", "is", "my", "country"]

Index Word Even? Result
0 india INDIA
1 is is
2 my MY
3 country country

Result: ['INDIA', 'is', 'MY', 'country']


Solution approaches

def alternate_upper(sentence: str) -> list:
    words = sentence.split()
    return [w.upper() if i % 2 == 0 else w for i, w in enumerate(words)]

enumerate gives both index and word. The ternary applies upper() only on even indices.

def alternate_upper(sentence: str) -> list:
    words = sentence.split()
    result = []
    for i, w in enumerate(words):
        if i % 2 == 0:
            result.append(w.upper())
        else:
            result.append(w)
    return result

Explicit loop -each step visible.

def alternate_upper(sentence: str) -> list:
    words = sentence.split()
    return list(map(
        lambda pair: pair[1].upper() if pair[0] % 2 == 0 else pair[1],
        enumerate(words)
    ))

map applies the lambda to each (index, word) pair from enumerate. Functional style -no explicit loop or comprehension.

def alternate_upper(sentence: str) -> list:
    words = sentence.split()
    words[::2] = [w.upper() for w in words[::2]]
    return words

words[::2] selects every other word starting from index 0. Uppercase them all, assign back via slice assignment. Compact -only the even-index words are touched.


Key takeaways

01

enumerate() for index + value

for i, w in enumerate(words) gives both the index and the word. Use it whenever you need to make decisions based on position.

02

Step slicing for alternates

words[::2] selects every even-index element. Assigning back with words[::2] = [...] updates only those positions -no loop needed.

03

Return a list, not a string

The problem asks for a list. sentence.split() already gives a list -don't accidentally join() it back into a string before returning.