Python Lists Homework

  • After going through the lists lesson work on these hacks in your own repository

Hack 1 – Add Up Numbers

Make a list of numbers. Write code to:

  1. Find the total sum.
  2. Find the average.

numbers = [4, 7, 1, 9, 6, 7, 10]

total = sum(numbers)

print(total)  # Output: 44


44

Hack 2 – Count Repeats

Make a list with repeated items. Write code to count how many times each item appears.

# Hack 2 – Count Repeats
items = ["cat", "dog", "cat", "bird", "bird", "bird"]

# Write your code here:
counts = {}

for item in items:
    if item in counts:
        counts[item] += 1
    else:
        counts[item] = 1

print(counts)
# Output: {'cat': 2, 'dog': 1, 'bird': 3}
{'cat': 2, 'dog': 1, 'bird': 3}

Hack 3 – Keep Only Evens

Make a list of numbers. Write code to create a new list with only even numbers.

# Hack 3 – Keep Only Evens
numbers = [3, 8, 5, 12, 7, 9, 13, 31, 66, 18]

# Write your code here:
evens = [n for n in numbers if n % 2 == 0]

print(evens)
# Output: [8, 12, 66, 18]
[8, 12, 66, 18]