for loops – iterating over items (slides)

CSc 110 - the other type of for loop

Review of for in range():

for n in range(5):
  print(n)
0
1
2
3
4
numbers = [2, 1, 4, 6, 23, 2]
for i in range(len(numbers)):
  print(numbers[i])
2
1
4
6
23
2

Introducing for x in string:

string = "hello"
for n in string:
  print(n)
h
e
l
l
o

Introducing for x in list:

numbers = [2, 1, 4, 6, 23, 2]
for n in numbers:
  print(n)
2
1
4
6
23
2

Write a function

Modify your count_chars function. Use for x in string instead of for x in range(len(string)).

assert count_chars("") == {}
assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}

Write a function – solution

def count_chars(string):
  counts = {}
  for char in string:
    if char in counts:
      counts[char] += 1
    else:
      counts[char] = 1
      
  return counts

def main():
  assert count_chars("") == {}
  assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}
  print("Passed all tests.")

main()
Passed all tests.

A Note on two methods

for i in range(len(list)): VS. for x in list:

  • Mutate the list: option 1 (need to use index i to mutate)
numbers = [2, 1, 4]
for i in range(len(numbers)):
  numbers[i] += 1
numbers
[3, 2, 5]
  • Get the values: both options
numbers = [2, 1, 4]
for n in numbers:
  print(n)
2
1
4

Write a function

It returns a dictionary that maps each negative value in numbers to its frequency in numbers.

assert tally_negatives([1, -2, 0, -4, -2]) == {-2: 2, -4: 1}
assert tally_negatives([]) == {}

Write a function – solution

def tally_negatives(numbers):
  tally = {}
  for n in numbers:
    if n < 0:
      if n not in tally:
        tally[n] = 0
      tally[n] += 1
  return tally

def main():
  assert tally_negatives([1, -2, 0, -4, -2]) == {-2: 2, -4: 1}
  assert tally_negatives([]) == {}
  print("Passed all tests.")
  
main()
Passed all tests.

Iterating a dictionary

Iterating keys:

scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10}
for key in scores:
  print(key)
A
B
C
D

Another option: dict.keys():

scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10}
for key in scores.keys():
  print(key)
A
B
C
D

Iterating a dictionary

Iterating values: dict.values():

scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10}
for value in scores.values():
  print(value)
10
25
27
10

Iterating both keys and values: dict.items()

scores = {'A': 10, 'B': 25, 'C': 27, 'D': 10}
for key, value in scores.items():
  print(key, value)
A 10
B 25
C 27
D 10

Write a function

It returns a list with all the keys and values in the dictionary.

Test cases:

assert keys_and_values({'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}) == \
    ['A', 10, 'B', 25, 'C', 27, 'D', 10, 'E', 5]

Write a function – solution

def keys_and_values(dictionary):
  new_list = []
  for key, value in dictionary.items():
    new_list.append(key)
    new_list.append(value)
  return new_list

def main():
  assert keys_and_values({'A': 10, 'B': 25, 'C': 27, 'D': 10, 'E': 5}) == ['A', 10, 'B', 25, 'C', 27, 'D', 10, 'E', 5]
  
main()

Quiz 07

current time

You have 10 minutes to complete the quiz.

No need to write main() function.

Write a function

It mutates dict_1, by adding to it all key-values pairs in dict_2. If a key is in both dictionaries, the values are added.

Test cases:

dict_1 = {"a": 20, "e": 5}
dict_2 = {"e": 10, "i": 2}
assert merge_dictionaries(dict_1, dict_2) == {"a": 20, "e": 15, "i": 2}

Write a function – solution

def merge_dictionaries(dict_1, dict_2):
  for key, value in dict_2.items():
    if key in dict_1:
      dict_1[key] += value
    else:
      dict_1[key] = value
  return dict_1
      
def main():
  dict_1 = {"a": 20, "e": 5}
  dict_2 = {"e": 10, "i": 2}
  assert merge_dictionaries(dict_1, dict_2) == {"a": 20, "e": 15, "i": 2}
  
main()

Write a function

It mutate the list, multiply every number by 2. It returns the highest value in the mutated list.

Test cases:

assert max_list([2, 2, 1]) == 4
assert max_list([5, 2, 1]) == 10
assert max_list([]) == None

Write a function – solution 1

def max_list(numbers):
    max = None
    for i in range(len(numbers)):
        numbers[i] *= 2
    for n in numbers:
        if max == None or n > max:
            max =  n
    return max

def main():
  assert max_list([2, 2, 1]) == 4
  assert max_list([5, 2, 1]) == 10
  assert max_list([]) == None
  print("pass")
  
main()
pass

Write a function – solution 1 continue

  • line 3: can we use for x in list?

  • line 5: can we use for i in range(len(list))?

def max_list(numbers):
    max = None
    for i in range(len(numbers)):
        numbers[i] *= 2
    for n in numbers:
        if max == None or n > max:
            max =  n
    return max

Write a function – solution 2

def max_list(numbers):
    max = None
    for i in range(len(numbers)):
        numbers[i] *= 2
        if max == None or numbers[i] > max:
            max = numbers[i]
    return max

def main():
  assert max_list([2, 2, 1]) == 4
  assert max_list([5, 2, 1]) == 10
  assert max_list([]) == None
  print("pass")
  
main()
pass

Write a function – solution 2 continue

  • line 3: can we use for x in list?
def max_list(numbers):
    max = None
    for i in range(len(numbers)):
        numbers[i] *= 2
        if max == None or numbers[i] > max:
            max = numbers[i]
    return max