A packing list must print one instruction for each item.
What You Need to Understand
A for loop visits each element of a list in sequence. The loop variable is assigned to the current value; you do not need to manage an index unless you actually need positions.
When to Use It
A packing list must print one instruction for each item.
Step-by-Step Python Example
items = ["cable", "adapter", "mouse"]
for item in items:
print(f"Pack: {item}")
How the Example Works
The loop body runs once for each of the three list elements. Indentation controls which statement belongs to the loop.
Example Output
Pack: cable
Pack: adapter
Pack: mouse
1 red
2 blue
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
for position, item in enumerate(["red", "blue"], start=1):
print(position, item)
Important Behavior and Edge Cases
Changing the collection while looping can skip or repeat items. Do not write for index in range(len(items)) unless position access is needed.
Try It Yourself
Print each item with an increasing number using enumerate(items, start=1).
Common Beginner Mistakes
- Changing the collection while looping can skip or repeat items. Do not write
for index in range(len(items))unless position access is needed. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- A
forloop visits each element of a list in sequence. - The loop body runs once for each of the three list elements.
- Changing the collection while looping can skip or repeat items.