Python Iterators
You have three words in a row: cup, then pen, then book. You want one word at a time, starting with cup. The first line on the screen will be cup.
items = ["cup", "pen", "book"]
walk = iter(items)
print(next(walk))
The screen shows cup. cup is the first of the three words. walk = iter(items) walks those words in order. print(next(walk)) writes the next word, and that word is cup. pen is not written. book is not written. The program is done. There is no second line.
items = ["cup", "pen", "book"]
walk = iter(items)
print(next(walk))
print(next(walk))
print(next(walk))
This is a second program. The screen shows three lines. The first line is cup. The second line is pen. The third line is book. The first print(next(walk)) writes cup. The second print writes pen, the next word. It does not write cup again. The third print writes book. One print writes one word. The program is done. There is no fourth line.
You can now take the first word, then the next word. The first screen is cup. The second screen is cup, then pen, then book. The next page checks that a result matches the result you wanted.
One word, then the next
The first screen is cup. The second screen is cup, then pen, then book. Each print writes one word. The next page checks that a result matches the result you wanted.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top