Lists Hacks Python
Categories: PythonThis is a CSP Hacks notebook based on the lists lesson
Python Lists Homework
- After going through the Python 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]
# Write your code here:
# Calculate sum
total = 0
for score in numbers:
total += score
print(f"Total points: {total}") # 44
# Calculate average
average = total / len(numbers)
print(f"Average score: {average}") # 6.29
Total points: 44
Average score: 6.285714285714286
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:
# Create empty dictionary to store counts
frequency = {}
# Count each item
for items in items:
if items in frequency:
frequency[items] += 1
else:
frequency[items] = 1
print(frequency)
# 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]
# Create empty list for Even Numbers
EvenNumbers = []
# Check each number
for num in numbers:
if num % 2 == 0: # Check if number is even
EvenNumbers.append(num)
print(EvenNumbers) # [8, 12, 66, 18]
[8, 12, 66, 18]