Title here
Summary here
Here we use `for` loops to sum the numbers in a slice. Arrays work like this too.
```python
nums = [2, 3, 4]
sum = 0
for num in nums:
sum += num
print("sum:", sum)
for
loops on arrays and slices provide 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("index:", i)
for
loops on dictionaries iterate over key/value pairs.
kvs = {"a": "apple", "b": "banana"}
for k, v in kvs.items():
print(f"{k} -> {v}")
for
loops can also iterate over just the keys of a dictionary.
for k in kvs:
print("key:", k)
for
loops on strings iterate over Unicode code points. The first value is the starting byte index of the character and the second the character itself.
for i, c in enumerate("go"):
print(i, c)
Running the code above yields:
$ python range_over_builtin_types.py
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 g
1 o