CS 111 w20 lecture 9 outline

1 Poll

data = [[1,2],[3,4],[5,6]]
acc = 0
for x in data:
    for num in x:
        acc = acc + num
print(acc)

What might nested lists be useful for?

2 Concatenation

  • We can use + to combine two lists into a single list
nums1 = [3, 9, 2]
nums2 = [4, 5, 6]
print(nums1 + nums2) # prints [3, 9, 2, 4, 5, 6], not [7, 14, 8]
  • How would you write code to do the pairwise addition?

3 Contains

Write a function contains that takes a list items and another parameter x. contains should return True if an element of items has the same value as x, otherwise it should return False.

def contains(items, x):
    for item in items:
        if x == item:
            return True
    return False

3.1 in operator

Python gives us a built-in shortcut for the function we wrote above: x in items returns the same result as contains(items, x)

4 Strings

  • a sequence of characters just like a list is a sequence of elements
  • lists can contain anything, even a mix of different things, but strings only have characters
    • a character is a single letter, number, symbol, or blank
      • blanks: " " (space), "\t" (tab), "\n" (newline)
  • just like lists:
    • len returns the length
    • can loop over characters with for
    • use in to check for containment
    • access individual characters with indexes
    • concatenate with +
  • unlike lists
    • fixed, cannot be modifed
      • immutable vs mutable, more detail next week
    • in checks for matching substrings instead of single characters
      • [2, 3] in [1, 2, 3] is False because [2, 3] does not match any single element of the list
      • but "23" in "123" is True because "23" matches up with part of the string
  • Python provides lots of useful operations

5 Files

happy_file = open("happy_little_file.txt")
file_text = happy_file.read()
print(file_text)
happy_file.close()

new_file = open("another_happy_file.txt", "w")
new_file.write("this file is so happy\n") # need to include \n to make a newline
new_file.write("just happy to be a file\n")
new_file.close()

6 Debugging word_check.py

7 Extra Exercise

Write loops to print the following

X
XX
XXX
XXXX
XXXXX