Range Over Built in D Programming Language

Here we use for ... in to sum the numbers in a list. The arrays work like this too.

nums = [2, 3, 4]
sum = 0
for num in nums:
    sum += num
print(f"sum: {sum}")

for ... in on lists provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.

for i, num in enumerate(nums):
    if num == 3:
        print(f"index: {i}")

for ... in on dictionaries iterates over key/value pairs.

kvs = {"a": "apple", "b": "banana"}
for k, v in kvs.items():
    print(f"{k} -> {v}")

for ... in can also iterate over just the keys of a dictionary.

for k in kvs:
    print(f"key: {k}")

for ... in on strings iterates over characters. The enumerate function provides both the index and character itself.

for i, c in enumerate("go"):
    print(i, ord(c))