Docsity

Range Loops,Lists - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download Range Loops,Lists - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • More range loops

HW

  • HW 6 due
  • HW 7 out
  • Project 1 due
  • Project 2 out

Exercise: Use range to create the following lists

  1. [0, 1, 2, 3, 4] ... range(5)
  2. [1, 3, 5, 7, 9] ... range(1, 10, 2)
  3. [0, 3, 6, 9] ... range(0, 10, 3)
  4. [4, 3, 2, 1] ... range(4, 0, -1)
  5. [10, 8, 6, 4, 2] ... range(10, 1, -2)
  6. [] ... range(0)

Exercise: Using range

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