Range Over Built in Fortress

Our program demonstrates how to iterate over elements in various built-in data structures. Here’s the translated code and explanation.

# Import the necessary module
print()  # only for output formatting in the explanation

# Here we use a list to sum the numbers.
nums = [2, 3, 4]
sum = 0
for num in nums:
    sum += num
print("sum:", sum)

# `enumerate` provides both the index and value.
for i, num in enumerate(nums):
    if num == 3:
        print("index:", i)

# Iterate over key/value pairs in a dictionary.
kvs = {"a": "apple", "b": "banana"}
for k, v in kvs.items():
    print(f"{k} -> {v}")

# Iterate over just the keys of a dictionary.
for k in kvs.keys():
    print("key:", k)

# Iterate over Unicode code points in a string.
for i, c in enumerate("go"):
    print(i, ord(c))

To run the program, simply execute the Python script.

$ python3 script.py
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

The program sums numbers in a list, finds the index of a specific value, iterates over key/value pairs and keys in a dictionary, and iterates over Unicode code points in a string. This covers various ways to iterate over different data structures in Python.