Iterating over strings in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we go through each letter in a word or sentence, we want to know how the time it takes grows as the word gets longer.
We ask: How does the work change when the string has more characters?
Analyze the time complexity of the following code snippet.
text = "hello world"
for char in text:
print(char)
# This code prints each character in the string one by one.
This code goes through each letter in the string and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the string.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work grows directly with the number of characters. Double the characters, double the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the length of the string.
[X] Wrong: "Looping over a string is instant no matter how long it is."
[OK] Correct: Each character still needs to be looked at one by one, so longer strings take more time.
Understanding how looping through strings scales helps you explain your code clearly and shows you know how programs handle data as it grows.
"What if we nested another loop inside to compare each character with every other character? How would the time complexity change?"
Practice
for letter in "hello":
print(letter)Solution
Step 1: Understand the for loop over a string
The loop goes through each character in the string "hello" one by one.Step 2: Print each character
Inside the loop, each letter is printed on its own line.Final Answer:
Prints each letter of the word 'hello' on a new line -> Option AQuick Check:
Loop over string prints letters individually [OK]
- Thinking the whole string prints at once
- Confusing string length with letters
- Believing strings can't be looped
text?Solution
Step 1: Identify correct for loop syntax for strings
In Python, to loop over characters in a string, usefor variable in string:.Step 2: Check each option
for char in text:uses correct syntax. The other options use invalid syntax like 'to' instead of 'in', range() on a string, or non-existent .length attribute.
print(char)Final Answer:
for char in text:
print(char) -> Option CQuick Check:
Correct for loop syntax over string is for char in text:
print(char) [OK]
- Using range() on a string directly
- Trying to use .length instead of len()
- Using incorrect loop keywords
word = "code"
result = ""
for ch in word:
result += ch.upper()
print(result)Solution
Step 1: Loop through each letter in 'code'
The loop takes each character: 'c', 'o', 'd', 'e'.Step 2: Convert each letter to uppercase and add to result
Each letter is changed to uppercase ('C', 'O', 'D', 'E') and added to the empty string result.Final Answer:
CODE -> Option BQuick Check:
Uppercase each letter and join = CODE [OK]
- Not converting letters to uppercase
- Printing original string instead of result
- Using += without initializing result
text = "hello"
for i in text:
print(text[i])Solution
Step 1: Understand the loop variable 'i'
Here, 'i' takes each character from 'text', so 'i' is a letter, not an index.Step 2: Using 'text[i]' causes error
Since 'i' is a letter, using it as an index causes a TypeError because string indices must be integers.Final Answer:
Using 'i' as index causes TypeError -> Option DQuick Check:
Loop variable is letter, not index, so indexing fails [OK]
- Assuming loop variable is index
- Trying to index string with a character
- Confusing loop variable with range
sentence. Which code correctly does this?Solution
Step 1: Check vowel membership correctly
count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) checks if each character is in the string of vowels (both lowercase and uppercase), which is correct.Step 2: Verify counting logic
count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) increments count correctly when a vowel is found and prints the total count.Final Answer:
count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) -> Option AQuick Check:
Use 'in' with vowel string and increment count [OK]
- Using '==' to compare with multiple vowels
- Checking membership incorrectly with list without uppercase
- Not incrementing count properly
