CS 111 w20 lecture 14 outline

1 Recap

  • notional machine
  • arithmetic, cpu
  • assignment, labels in memory
  • print, send data to screen
  • functions, separate definition and execution
    • call, pass arguments to function execution, move instruction pointer
    • return, send data to program that called the function, move instruction pointer
    • scope, data stays within the function (except for aliases of mutable data)
  • conditionals, control instruction pointer
    • Boolean values
    • Boolean operators
  • loops, iteration
    • for, definite
    • while, indefinite
  • sequences
    • lists
    • strings
    • tuples
    • indexing
    • len
    • range
    • today: slicing

2 Poll

def foo(vals):
    result = []
    for i in range(1, len(vals) - 1):
        result.append(vals[i])
    return result

v = [0, 2, 4, 6, 0]
print(foo(v))

3 Slicing

  • returns a new sequence with the elements from a portion of an existing sequence
  • uses the form sequence[start:end:step]
    • like range, has a start, end, and step size
    • also like range, we can leave one or more of these out and Python will use a default value
      • start:end:step
      • start:end:[1]
      • start:[len]:[1]
      • [0]:end:[1]
      • [0]:[len]:[1]
      • [:] to copy

3.1 Poll

  • What slice performs the same operation as foo?

3.2 Practice

fruits = ["Apple","Banana","Blueberry","Cherry"]

# last two elements
print(fruits[-2:])

# middle two
print(fruits[1:3])

# first and third
print(fruits[:3:2])

# reversed
print(fruits[3::-1])

3.3 Special Cases

3.3.1 Empty Slice

When you can't get from start to end with the given step, the result is an empty list, []

  • fruits[3:1]
  • fruits[-1:1]
  • fruits[-1:-3]

3.3.2 Past the End

When a slice would go past the end of the list, the slice works as normal through the end of the list

  • fruits[:100]

3.3.3 Everything is Backwards for Negative Slices

  • fruits[100::-1]
  • fruits[1:3:-1]
  • fruits[3:1:-1]

3.4 Slicing Strings

Slicing can be applied to any sequence, not just lists. Write code that reverses each half of a string separately and replaces the existing string with the reversed halves combined. If we start with

s = "fly, you fools!"

then at the end, print(s) should display oy ,ylf!sloof u

s = "fly, you fools!"
s = s[len(s) // 2 - 1::-1] + s[len(s):len(s) // 2 - 1:-1]

Unlike going through the end of the list, we don't have a way to specify "go through the beginning" (0 leaves out the first element, -1 refers to the end), so the only way to achieve it is to omit it.