Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Iterating over a list
Modifying lists
Working with multiple lists
Congratulations
16. Summary

## Instruction

Well done! It's time to wrap things up. Let's summarize what we've learned before we take the quiz.

1. Use a for loop 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
2. You can usethe enumerate() function with a for loop.
first_sum = 0
second_sum = 0
for i, number in enumerate(numbers):
if i < 2:
first_sum += number
else:
second_sum += number

3. If you want to update list elements, iterate over the indexes.
for i in range(len(numbers)):
numbers[i] = ...
4. 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]

5. To safely delete list elements, iterate over a copy of the list using [:].
for number in numbers[:]:
numbers.remove(number)
6. 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)
7. 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]:
...
8. 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):
...
9. 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. 