Range Over Built in CLIPS

Ranging Over Built-in Types

In this example, we will demonstrate how to iterate over different built-in data structures using Python.

if __name__ == "__main__":
    # Using range to sum the numbers in a list. Arrays work like this too.
    nums = [2, 3, 4]
    sum = 0
    for num in nums:
        sum += num
    print("sum:", sum)

    # Using range to get the index and value from a list.
    for i, num in enumerate(nums):
        if num == 3:
            print("index:", i)

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

    # Using range to iterate over keys in a dictionary.
    for k in kvs.keys():
        print("key:", k)

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

Explanation

  1. Summing the numbers in a list: Here, we iterate over the elements of the list nums and calculate the sum of its elements.

    nums = [2, 3, 4]
    sum = 0
    for num in nums:
        sum += num
    print("sum:", sum)
  2. Getting the index and value from a list: We use enumerate to get both the index and the value while iterating over the list. When the value equals 3, we print the index.

    for i, num in enumerate(nums):
        if num == 3:
            print("index:", i)
  3. Iterating over key/value pairs in a dictionary: Using the .items() method, we iterate over the key/value pairs of the dictionary kvs, and print each pair.

    kvs = {"a": "apple", "b": "banana"}
    for k, v in kvs.items():
        print(f"{k} -> {v}")
  4. Iterating over keys in a dictionary: We iterate over the keys of the dictionary kvs using the .keys() method.

    for k in kvs.keys():
        print("key:", k)
  5. Iterating over Unicode code points in a string: We use enumerate to get both the index and the Unicode code point (rune) of each character in the string "go". We use ord() to get the Unicode code point of each character.

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

Running the Program

To run the program, save the code in a file named range_over_builtin_types.py and execute it with Python.

$ python range_over_builtin_types.py

This will output:

sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111