Lists Hacks Python
This is a CSP Hacks notebook based on the lists lesson
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:
- Find the total sum.
- Find the average.
# Hack 1 – Add Up Numbers
numbers = [4, 7, 1, 9, 6, 7, 10]
total = 0
# Write your code here:
for number in numbers:
total += number
print("The total is:", total)
The total is: 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:
itemCounts = {}
for item in items:
if item in itemCounts:
itemCounts[item] += 1
else:
itemCounts[item] = 1
print("Item counts:", itemCounts)
Item counts: {'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]
new_numbers = []
# Write your code here:
for number in numbers:
if number % 2 == 0:
new_numbers.append(number)
print("Even numbers:", new_numbers)
Even numbers: [8, 12, 66, 18]