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:
"india is my country"
['INDIA', 'is', 'MY', 'country']
"this is a test case"
['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.
Key takeaways¶
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.
Step slicing for alternates
words[::2] selects every even-index element. Assigning back with words[::2] = [...] updates only those positions -no loop needed.
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.