Looping with lists and dictionaries and index and range

Overview

For loops can be used to get each element of a string or dictionary, which can be very useful

You can also use the range function with for loops and call on an element with its index

Looping through a string/dictionary with for loops

names = ["John", "Abraham", "Bill", "Henry"]

for name in names:
    print(name)
John
Abraham
Bill
Henry
%%js
const names = ["John", "Abraham", "Bill", "Henry"];

for (const name of names) {
    console.log(name);
}
<IPython.core.display.Javascript object>

In this example, we first created a list. Then, using the for loop, we iterate through each index of the list. For each iteration, we print the corresponding name in our list. So, on the first iteration, we will print the first name in our list.

student_info = {
    "John": 15,
    "Abraham": 17,
    "Bill": 14,
    "Henry": 16
}

print(student_info.items())

for name, age in student_info.items():
    print(f"{name} is {age}")
dict_items([('John', 15), ('Abraham', 17), ('Bill', 14), ('Henry', 16)])
John is 15
Abraham is 17
Bill is 14
Henry is 16
%%js
student_info = {
    'John': 15,
    'Abraham': 17,
    'Bill': 14,
    'Henry': 16
};

console.log(student_info.items());

for (name, age in student_info.items()) {
    console.log(name, " is ", age);
}
<IPython.core.display.Javascript object>

This is a bit more complicated. Instead of one temporary variable, we create two because we want to take two different values from the dictionary in each iteration. The name is the item in the dictionary and the age is the value. As you see in the list of items in the dictionary, since each item has two values, we can use two variables to get each. Then, we use a formatted string to print the name and age of each student.

Popcorn Hack #4

Create a dictionary and create a for loop that runs through each key and value of the dictionary For each iteration, print the key and value as well as a message of your choice

(Use Example Above)

Using index with range and len functions in a for loop

test_string = "Bobby James"

x = 0 

for index in range(len(test_string)):
    x += index
    print(x)
0
1
3
6
10
15
21
28
36
45
55

This is a different way to use for loops. We create a string and then use ‘range’ to run the for loop for as many times as the length of the string. The count for len starts at 0, so each time it would count up from 0 by 1, as you can see in the addition to x each time.

–>