CMU 15-110: Principles of Computing
1d Lists (Part 1)


  1. Creating Lists
  2. List Functions
  3. Accessing Elements
  4. Finding Elements
  5. Adding Elements
  6. Removing Elements
  7. Looping Over Lists
  8. Example: The Locker Problem

  1. Creating Lists
    print('Empty lists:') a1 = [ ] a2 = list() print(' ', a1, a2) print('Non-empty lists:') a3 = [2, 3, 5, 7] a4 = ['mixed types', True, 42] print(' ', a3, a4) print('Variable-length lists:') a5 = [42] * 10 print(' ', a5) print('Converting non-lists to lists:') a6 = list(range(5)) a7 = list('yes!') print(' ', a6, a7)

  2. List Functions
    a = [ 2, 3, 5, 2 ] print('a = ', a) print('len =', len(a)) print('min =', min(a)) print('max =', max(a)) print('sum =', sum(a))

  3. Accessing Elements
    a = [2, 3, 5, 7, 11, 13] print('Indexing works just like strings:') print(' a[0] =', a[0]) print(' a[-1] =', a[-1]) print('Slicing also works just like strings:') print(' a[1:3] =', a[1:3]) print(' a[3:] =', a[3:])

  4. Finding Elements
    a = [ 2, 3, 5, 2, 6, 5, 5, 7, 5 ] print('in, not in, count, and index all work just like strings:') print(' ', 3 in a) print(' ', 3 not in a) print(' ', a.count(5)) print(' ', a.index(5))

  5. Adding Elements
    • Using append is destructive (modifies the list)
      a = [ 2, 3 ] a.append(7) print(a)

    • Using + is non-destructive (creates a new list)
      a = [ 2, 3 ] b = a + [ 7 ] print(a) print(b)

  6. Removing Elements
    • Using remove
      a = [ 2, 3, 5, 4, 5 ] print('a =', a) a.remove(5) print("After a.remove(5), a=", a) a.remove(5) print("After another a.remove(5), a=", a)

    • Using pop
      a = [ 2, 3, 4, 5 ] print('a =', a) print('pop with no argument removes (pops) the last value:') v = a.pop() print(' We just popped:', v) print(' And now a =', a) print('pop with an argument removes the value at that index:') v = a.pop(1) print(' We just popped:', v) print(' And now a =', a)

  7. Looping Over Lists
    • Looping over items
      a = [ 2, 3, 5, 7 ] print('Here are the items in a:') for item in a: print(item)

    • Looping over indexes
      a = [ 2, 3, 5, 7 ] print('Here are the items in a with their indexes:') for i in range(len(a)): print('a[', i, '] =', a[i])

  8. Example: The Locker Problem
    def lockerProblem(lockers): isOpen = [ False ] * (lockers+1) students = lockers for student in range(1,students+1): for locker in range(student, lockers+1, student): isOpen[locker] = not isOpen[locker] openLockers = [ ] for locker in range(1, lockers+1): if isOpen[locker]: openLockers.append(locker) return openLockers print(lockerProblem(2000))