Understanding FOR Loop Destinations in Programming

FOR Loop Destination: The Iteration Source Explained

In programming, a FOR destination (more commonly called the iterable or iteration source) defines the collection of values that a loop variable will sequentially assume during each iteration of a FOR loop.

General Syntax

for identifier in destination:
    # loop body
    commands

Where:

  • identifier — the loop variable (takes each value from destination)
  • destination — any iterable object (the FOR destination)
  • loop body — commands executed for each value

Common FOR Destination Types (Python Examples)

1. List Iteration

numbers = [1, 2, 3, 4]
for number in numbers:
    print(number)
# Output: 1, 2, 3, 4 (each on new line)

2. Range Object (Numeric Sequences)

for number in range(5):
    print(number)
# Output: 0, 1, 2, 3, 4

3. String Iteration (Character by Character)

word = "Hello"
for letter in word:
    print(letter)
# Output: H, e, l, l, o

4. File Object (Line by Line)

with open("myfile.txt", "r") as file:
    for line in file:
        print(line.strip())

5. Dictionary Iteration

ages = {"Alice": 30, "Bob": 25}
for name, age in ages.items():
    print(f"{name} is {age} years old")

6. Set Iteration

unique_numbers = {1, 2, 3, 2, 1}
for num in unique_numbers:
    print(num)
# Output: 1, 2, 3 (order not guaranteed)

Key Concepts

  • Iterable Protocol: Any object implementing __iter__() or __getitem__() can be a FOR destination
  • Lazy Evaluation: Generators and range objects compute values on-demand, saving memory
  • Unpacking: Multiple identifiers can unpack tuple elements: for x, y in points:
  • Else Clause: Python's for-else executes else block if loop completes without break

Language Variations

While syntax differs, the concept exists across languages:

  • JavaScript: for (const item of iterable)
  • Java: for (Type item : collection)
  • C++: Range-based for (auto& item : container)
  • C#: foreach (var item in collection)
Copyright Wanderlust World © https://www.ynyoo.com