Loops with nested data structures

Question Click to View Answer

What does the following code print?

numbers = [
    [10, 20],
    [30, 40],
]

result = 0

for i in numbers:
    for j in i:
        result = result + j

print(result)

100 is printed.

This code uses nested for loops to iterate over every item in numbers.

Run this code snippet to better understand how nested for loops work.

for i in numbers:
    print("outer loop")
    print(i)
    for j in i:
        print("inner loop")
        print(j)

What does the following code print?

animals = [
    {"species": "dog", "is_mammal": True},
    {"species": "fish", "has_hair": "False"},
]

result = []

for a in animals:
    result.append(a["species"])

print(result)

['dog', 'fish'] is printed.

A for loop is used to iterate through all the dictionaries in the animals list and append the species to the result list.

What does the following code print?

from functools import reduce

nums = [
    [1, 2, 13, 15],
    [30, 40],
]

res = []

for i in nums:
    r = reduce(lambda x, y: x + y, i)
    res.append(r)

print(res)

[31, 70] is printed.

A for loop is used to iterate over each sub-list. reduce is used to sum all of the numbers in each sub-list and append the sum to the res list.

What does the following code print?

letters = [
    ["a", "b", "c", "d"],
    ["e", "f"],
]

res = []

for i in letters:
    for j in i:
        res.append(j)

print(res)

['a', 'b', 'c', 'd', 'e', 'f'] is printed.

The nested loop flattens the nested list data structure into a single list.

What does the following code print?

stuff = [
    ["aa", "bbb", "c", "d"],
    ["eeeee", "ff"],
]

biggest = ""

for i in stuff:
    for j in i:
        biggest = biggest if len(biggest) > len(j) else j

print(biggest)

"eeeee" is printed.

The biggest variable is initially assigned to the empty string.

A nested loop is used to iterate the nested data structure and continuously update the biggest variable with the longest string.

What does the following code print?

fun_numbers = [
    [8, 13, 17],
    [98, 99],
]

is_odd = lambda y: y % 2 != 0
maybe = map(lambda b : list(filter(is_odd, b)), fun_numbers)

print(list(maybe))

[[13, 17], [99]] is printed.

We iterate through the fun_numbers array and filter out all the numbers that aren't even.

Nesting filter() in map() is ugly so Python has some other libraries that can make this type of code cleaner.