Instruction
Well done! It's time to wrap things up. Let's summarize what we've learned before we take the quiz.
- Use a
forloop to iterate over a list. You may need one or more variables defined before the loop.numbers = [2, 45, 32, 1] sum = 0 for number in numbers: sum += number
- You can usethe
enumerate()function with aforloop.first_sum = 0 second_sum = 0 for i, number in enumerate(numbers): if i < 2: first_sum += number else: second_sum += number - If you want to update list elements, iterate over the indexes.
for i in range(len(numbers)): numbers[i] = ...
- To change the element order, iterate over the indexes.
for i in range(0, len(numbers), 2): numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
- To safely delete list elements, iterate over a copy of the list using
[:].for number in numbers[:]: numbers.remove(number)
- When creating a new list based on an existing one, you will typically need an empty list before the loop with an
append()function inside it.neg_numbers = [] for number in numbers: neg_numbers.append(-1 * number)
- To compare two same-sized lists element by element, iterate over the indexes of either list.
numbers1 = [4, 98, 23, 43] numbers2 = [2, 45, 32, 1] for i in range (len(numbers1)): if numbers1[i] > numbers2[i]: ... - When comparing two lists with different sizes, watch out for
IndexErrors: iterate over the shorter list or check if the current index is within the bounds.numbers1 = [2, 45] numbers2 = [2, 45, 32, 1]
- iterate over the shorter list
for i in numbers1: ...
- check the index inside
for i in numbers2: if i < len(numbers1): ...
- iterate over the shorter list
- When merging sorted lists or searching for common elements, you will typically need a while loop and two variables to store the current list indexes.
i, j = 0, 0 while i < len(list1) and j < len(list2): if ...: i += 1 if ...: j += 1
Quite a lot! All right, it's time for a short quiz.
Exercise
Click to continue.



