


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Today ...
HW
Exercise: Write a function make spam list that takes a list of strings and returns a new list with the string "spam" added to the end of each list item n times, where the item is the nth element of the list. For example:
my_list = ["hi", "bye"] my_result = spam_list(my_list) print(my_result) ["hi spam", "bye spam spam"]
Answer:
def spam_list(a_list): new_list = [] # accumulator the_length = len(a_list) for i in range(the_length): s = " spam" * (i + 1) new_list.append(a_list[i] + s) return new_list
Q: Can you think of a way to do this using a value loop instead?
def spam_list(a_list): new_list = [] i = 1 for elem in a_list: s = " spam" * (i + 1) new_list.append(elem + s) i = i + 1 return new_list